package basicSorted.com;
import java.util.Arrays;
/**
* @Author Kyrie
* @Description
* 二叉堆实现优先队列
**/
public class Code04_PriorityQueue {
public static int[] arr;
public static int size;
public Code04_PriorityQueue(){
arr = new int[32];
}
//入队
public static void enQueue(int key){
if(size >= arr.length){
resize();
}
arr[size++] = key;
upAdjust();
}
//出队
public static int deQueue() throws Exception{
if(size <= 0){
throw new Exception("the queue is empty!");
}
int head = arr[0];
arr[0] = arr[--size];
downAdjust();
return head;
}
public static void upAdjust(){
int childIndex = size - 1; //从数组末尾开始
int parentIndex = childIndex >>> 1;
//temp 保存叶子节点的值
int temp = arr[childIndex];
while(childIndex > 0 && temp > arr[parentIndex]){
//优化:无需真正交换,单向赋值即可
arr[childIndex] = arr[parentIndex];
childIndex = parentIndex; //更新childIndex的索引
parentIndex = parentIndex >>> 1; //继续找父节点
}
//父节点的值小于temp
arr[childIndex] = temp;
}
public static void resize() {
int newSize = size * 2;
arr = Arrays.copyOf(arr, newSize);
}
public static void downAdjust(){
int parentIndex = 0;
//temp的作用相同,用于最后赋值
int temp = arr[parentIndex];
int childIndex = 1;
while(childIndex < size){
int more = childIndex+1 < size && arr[childIndex+1] > arr[childIndex] ? childIndex+1 : childIndex;
more = arr[more] > arr[parentIndex] ? more : parentIndex;
if(parentIndex == more){
break; //父节点小于任何一个孩子的值,直接跳出
}
//交换
arr[parentIndex] = arr[more];
parentIndex = more;
arr[parentIndex] = temp;
childIndex = 2 * parentIndex + 1;
}
}
public static void main(String[] args) throws Exception {
Code04_PriorityQueue queue = new Code04_PriorityQueue();
enQueue(3);
enQueue(5);
enQueue(10);
enQueue(2);
enQueue(7);
System.out.println("出队元素:" + deQueue());
System.out.println("出队元素:" + deQueue());
/*
出队元素:10
出队元素:7
*/
}
}
堆实现优先队列
最新推荐文章于 2022-10-09 20:48:08 发布