1.简介
队列的特点是:先进先出(FIFO),也就是说,入队时,将新的元素置于队尾;出队时,队头元素最先被移出。
优先队列不再遵循先入先出的原则,它分为两种情况:
(1)最大优先队列:无论入队顺序如何,都是当前最大的元素优先出队
(2)最小优先队列:无论入队顺序如何,都是当前最小的元素优先出队
二叉堆是实现优先队列得基础,二叉堆中堆节点的“上浮”和“下沉”的时间复杂度都是O(logn),所以优先队列的入队和出队操作的时间复杂度都是O(logn)
2.代码实现
import java.util.Arrays;
public class PriorityQueue {
private int[] array;
private int size;
public PriorityQueue(){
array = new int[32];
}
/**
* 入队操作
* @param key 要插入的元素
*/
public void enQueue(int key){
//队列长度超出范围,扩容
if(size >= array.length){
resize();
}
array[size++] = key;
//将插入的元素放在叶子节点,接下来进行上浮的操作
upAjust();
}
/**
* 出队
* @return 出队的元素
* @throws Exception
*/
public int deQueue() throws Exception{
//判断队列是否为空
if(size <= 0){
throw new Exception("the queue is Empty!");
}
//获取堆顶元素
int head = array[0];
//让最后一个元素移动到堆顶
array[0] = array[--size];
downAdjust();
return head;
}
/**
* 上浮调整
*/
private void upAjust(){
int childIndex = size - 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 / 2;
}
array[childIndex] = temp;
}
/**
* 下沉调整
*/
private 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;
}
/**
* 扩容操作
* @return
*/
private void resize(){
//队列容量翻倍
int newSize = this.size * 2;
this.array = Arrays.copyOf(this.array, newSize);
}
public static void main(String[] args) throws Exception {
PriorityQueue priorityQueue = new PriorityQueue();
priorityQueue.enQueue(3);
priorityQueue.enQueue(5);
priorityQueue.enQueue(10);
priorityQueue.enQueue(2);
priorityQueue.enQueue(7);
System.out.println("出队元素:" + priorityQueue.deQueue());
System.out.println("出队元素:" + priorityQueue.deQueue());
}
}