优先级队列(PriorityQueue):
1.概念:
普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出 (first in, largest out)的行为特征。通常采用堆数据结构来实现。
2.优先级队列的一些基本方法(和队列(Queue)基本相同):
1.q.push(k);给q中插入元素k
2.q.pool();删除队q的第一个元素
3.q.peek();返回q的第一个元素
3.实现代码:
public class HeapDemo {
public int[] elem;
public int usedSize;
public HeapDemo() {
this.elem = new int[10];
}
//向下调整
public void adjustDown(int parent, int len) {
int child = 2*parent + 1;
//
while (child < len) {
//child+1<len是判断是否有右孩子
if (child + 1 < len && this.elem[child] < this.elem[child+1]) {
child++;
}
if (this.elem[child] > this.elem[parent]) {
int tmp = this.elem[child];
this.elem[child] = this.elem[parent];
this.elem[parent] = tmp;
parent = child;
child = 2*parent+1;
} else {
break;
}
}
}
//向上调整
public void adjustUp(int child){
int parent = (child-1)/2;
while(child > 0){
if(this.elem[child] > this.elem[parent]){
int tmp = this.elem[child];
this.elem[child] = this.elem[parent];
this.elem[parent] = tmp;
child = parent;
parent = (child-1)/2;
}else{
break;
}
}
}
public void push(int val){
if(isFull()){
this.elem =
Arrays.copyOf(this.elem,2*this.elem.length);//如果队列已满则2倍扩容
}
this.elem[this.usedSize] = val;
this.usedSize++;
adjustUp(this.usedSize-1);
}
public int poll(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
int ret = this.elem[0];
int tmp = this.elem[0];
this.elem[0] = this.elem[this.usedSize-1];
this.elem[this.usedSize-1] = tmp;
this.usedSize--;
adjustDown(0,this.usedSize);
return ret;
}
public int peek(){
if(isEmpty()){
throw new RuntimeException("队列为空!");
}
return this.elem[0];
}
public boolean isFull(){
return this.usedSize == this.elem.length;
}
public boolean isEmpty(){
return this.usedSize == 0;
}
//创建堆
public void creatBigHeap(int[] array) {
for (int i = 0; i < array.length; i++) {
this.elem[i] = array[i];
this.usedSize++;
}
for (int i = (this.usedSize-1-1)/2; i >= 0; i--) {
adjustDown(i, this.usedSize);
}
}
}
温馨提示:初次学习,不足之处之后学习到再进行完善补充。