import java.util.Arrays;
import java.util.PriorityQueue;
public class FirstQueue {
private static int[] array;
private static int size;
public FirstQueue() {
// 队列初始长度为32
array = new int[32];
}
private void enQueue(int key) {
// 队列长度超出范围,扩容
if (size >= array.length) {
resize();
}
array[size++] = key;
}
private int deQueue() throws Exception {
if (size <= 0) {
throw new Exception("这个队列是空的!");
}
// 获取堆顶元素
int head = array[0];
// 让最后一个元素移动到堆顶
array[0] = array[--size];
downAdjust();
return head;
}
/**
* 上浮调整
*
* @param array 待调整的堆
*/
private static void upAdjust(int[] array) {
int childIndex = array.length - 1;
int parentIndex = (childIndex - 1) / 2;
// temp保存插入的叶子节点值,用于最后的赋值
int temp = array[childIndex];
while (childIndex > 0 && temp < array[parentIndex]) {
// 无需真正交换,单向赋值即可
array[childIndex] = array[parentIndex];
childIndex = parentIndex;
parentIndex = (parentIndex - 1) / 2;
}
// 最后将值给它
array[childIndex] = temp;
}
/**
* 下沉调整
*
* @param array 待调整的堆
* @param parentIndex 要下沉的父节点
* @param lenght 堆得有效大小
*/
private static void downAdjust() {
// temp保存父节点值,用于最后赋值
int parentIndex = 0;
int temp = array[parentIndex];
int childIndex = 1;
// 左孩子
while (childIndex < size) {
// 如果有右孩子,且右孩子小于左孩子的值,则定位到右孩子
if (childIndex + 1 < size && array[childIndex] + 1 > array[childIndex]) {
childIndex++;
}
// 如果父节点则任何一个孩子的值,则直接跳出
if (temp >= array[childIndex]) {
break;
}
// 无需真正交换,单向赋值即可
array[parentIndex] = array[childIndex];
parentIndex = childIndex;
childIndex = 2 * childIndex + 1;
}
array[parentIndex] = temp;
}
private void resize() {
// 队列容量翻倍
int newSize = this.size = 2;
this.array = Arrays.copyOf(this.array, newSize);
}
// 测试
public static void main(String[] args) throws Exception {
FirstQueue firstQueue = new FirstQueue();
firstQueue.enQueue(3);
firstQueue.enQueue(5);
firstQueue.enQueue(10);
firstQueue.enQueue(2);
firstQueue.enQueue(7);
System.out.println("出队元素: "+firstQueue.deQueue());
System.out.println("出队元素: "+firstQueue.deQueue());
}
}
二叉堆之优先队列的实现
原创
©著作权归作者所有:来自51CTO博客作者幸运用户的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
优先队列-二叉堆-堆排序原理-Java相关API
完全二叉树概念除了最后一层,前面所有层都是满的最后一层是从左到右是一个二叉树堆
二叉树 数据结构 算法 java 队列 -
学习算法 - 优先级队列二叉堆实现i++ #define #include 优先队列 #ifndef
-
redis 列出key的value
第一章 Redis 快速入门 Redis是一个Key-Value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)和zset(有序集合)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操
redis 列出key的value redis 存储系统 cassandra memcached