队列的基本准则就是先进先出,优先队列有两种,一种就是最大优先队列,就是不管入队元素,先让队列里的最大值先出队,另一种就是最小优先队列,就是不管入队元素,先让队列里的最小的元素先出队,运用二叉堆的方法可以实现它,把队列里的元素调整成大顶堆或者小顶堆,最后获取堆顶的元素进行了。
package shujujiegou;
import java.util.Arrays;
/**
* 优先级队列
* @author TomCat
*
*/
public class PropertityQueue {
private int[] array;
private int size;
public PropertityQueue() {
//队列的初始长度为32
array=new int[32];
}
/**
* 入队
*/
private void enQueue(int key) {
if(size>=array.length) {
resize();
}
array[size++]=key;
upAdjust();
}
/**
* 出队
* @throws Exception
*/
private int deQueue() throws Exception {
if(size<=0) {
throw new Exception("队列为空");
}
//获取堆顶的元素
int head=array[0];
//最后一个元素移动到堆顶
array[0]=array[--size];
downAdjust();
return head;
}
private void downAdjust() {
// TODO Auto-generated method stub
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;
}
public void resize() {
int newSize=this.size*2;
this.array=Arrays.copyOf(this.array, newSize);
}
private void upAdjust() {
// TODO Auto-generated method stub
int childIndex=size-1;
int parentIndex=childIndex/2;
//temp用于保存插入叶子节点的值,用于最后的赋值操作
int temp=array[childIndex];
while(childIndex>0&&temp>array[parentIndex]) {
array[childIndex]=array[parentIndex];
childIndex=parentIndex;
parentIndex=parentIndex/2;
}
array[childIndex]=temp;
}
public static void main(String[] args) throws Exception {
PropertityQueue p=new PropertityQueue();
p.enQueue(1);
p.enQueue(5);
p.enQueue(2);
p.enQueue(3);
p.enQueue(10);
System.out.println("出队元素"+p.deQueue());
System.out.println("出队元素"+p.deQueue());
}
}