概念
1.和普通队列一样,有队头和队尾,并且从队头移动数据
2.数据项按照关键值有序,最小的数据项或者最大的数据项总是在队头,数据项插入时是有序的
图示
class PriorityQueue {
private int maxSize;//优先级队列最大容量
private int[] array;//使用数组实现优先级队列
private int cur;//队列最后元素所在位置
//初始化队列
public PriorityQueue(int maxSize) {
this.maxSize = maxSize;
array = new int[this.maxSize];
cur = -1; //初始化时,队列为空,cur=-1
}
//添加数据
public void insert(int value) {
if (isFull()) {
throw new RuntimeException("队列已满");
}
int j;
if (cur == -1) {//如果当前队列为空,则直接在队首插入,然后移动当前指针位置,使得cur=0
array[++cur] = value;
} else {
//队列不为空,倒序遍历数据,并进行比较,使得整个数组中的元素是有序的
for (j = cur; j >= 0; j--) {
if (value > array[j]) {
//如果要插入的元素大于当前元素,当前元素后移一位
array[j + 1] = array[j];
} else {
//遇到要插入的元素不大于当前元素,即找到可以插入的位置,跳出循环
break;
}
}
//在上面找到的位置插入新元素
array[j + 1] = value;
//使cur指向队列最后一个位置,(每加入一个,就移动一次)
++cur;
}
}
//从最小的一端移除数据
public int remove() {
if (isEmpty()) {
throw new RuntimeException("队列已空");
}
return array[cur--];
}
public void display() {
if (isEmpty()) {
throw new RuntimeException("队列已空");
}
for (int i = cur; i >= 0; i--) {
System.out.print(array[i] + "\t");
}
}
//判断是否为空队列
public boolean isEmpty() {
return cur == -1;
}
//判断是否已满
public boolean isFull() {
return cur == maxSize - 1;
}
}