1.1. 优先级队列的数据结构
如果我们给每个元素都分配一个数字来标记其优先级,不妨设较小的数字具有较高的优先级,这样我们就可以在一个集合中访问优先级最高的元素并对其进行查找和删除操作了。这样,我们就引入了优先级队列这种数据结构。 优先级队列(priorityqueue)是0个或多个元素的集合,每个元素都有一个优先权,对优先级队列执行的操作有(1)查找(2)插入一个新元素(3)删除一般情况下,查找操作用来搜索优先权最大的元素,删除操作用来删除该元素。对于优先权相同的元素,可按先进先出次序处理或按任意优先权进行。
1.2. Java实现
PriorityQueueTest |
package ch04;
public class PriorityQueueTest {
public static void main(String[] args) {
PriorityQueue queue = new PriorityQueue(10);
System.out.println("isEmpty: " + queue.isEmpty());
for (int i = 0; i < 10; i++) {
queue.insert(i);
}
System.out.println("isFull: " + queue.isFull());
while (!queue.isEmpty()) {
System.out.println(queue.remove());
}
}
}
class PriorityQueue {
private int[] arrInt;// 内置数组
private int nItems;// 数组中元素个数
public PriorityQueue(int size) {
this.arrInt = new int[size];
nItems = 0;
}
/**
* 判断优先级队列是否为空
*
* @return
*/
public boolean isEmpty() {
return 0 == nItems;
}
/**
* 判断优先级队列是否已满
*
* @return
*/
public boolean isFull() {
return nItems == arrInt.length;
}
/**
* 向优先级队列中插入一个元素
*
* @param item
*/
public void insert(int item) {
if (isFull()) {
throw new RuntimeException("优先级队列已满");
}
if (item == 0) {
arrInt[nItems] = item;
} else {
int j;
for (j = nItems - 1; j >= 0; j--) {
if (item > arrInt[j]) {
arrInt[j + 1] = arrInt[j];
} else {
break;
}
}
arrInt[j + 1] = item;
}
nItems++;
}
/**
* 获得优先级队列优先级最高的元素
*
* @return
*/
public int peek() {
return arrInt[nItems - 1];
}
/**
* 从优先级队列中移除一个元素
*
* @return
*/
public int remove() {
if (isEmpty()) {
throw new RuntimeException("优先级队列为空");
}
return arrInt[--nItems];
}
}
|
运行结果如下:
isEmpty: true
isFull: true
0
1
2
3
4
5
6
7
8
9