/**
* 优先级队列简单实现
* 采用数组实现
* 插入元素时需要进行key比较,找到索引位置
* 删除元素时,直接从顶端取出(优先级高的优先处理)
* @author gisliu
*
*/
public class PriorityQueue {
private int MAX_CAPACITY;
private int[] data;
private int items;
public PriorityQueue(int capacity){
MAX_CAPACITY = capacity;
data = new int[MAX_CAPACITY];
items = 0;
}
public PriorityQueue(){
this(10);
}
public void insert(int value){
if(isFull())
throw new FullQueueException();
if(items == 0){
data[items++] = value;
} else {
// int j = 0;
// while(data[j]>value){
// j++; // 步骤(1)找到插入的位置
// }
//
// for(int i=items;i>j;i--){
// data[i] = data[i-1]; // 步骤(2)整体移位,腾出一个空间
// }
// data[j] = value;
// 步骤(1)和步骤(2)可以合并
int i = 0;
for(i=items-1;i>=0;i--){
if(data[i] < value) {
data[i+1] = data[i];
} else {
break;
}
}
data[i+1] = value;
items++;
}
}
public int remove(){
if(isEmpty())
throw new EmptyQueueException("queue is empty");
return data[--items];
}
public boolean isEmpty(){
return (items == 0);
}
public boolean isFull(){
return (items == MAX_CAPACITY);
}
public int peek(){
return data[items-1];
}
public int size(){
return items;
}
public static void main(String[] args){
PriorityQueue priority = new PriorityQueue();
Random random = new Random();
for(int i=0;i<10;i++){
priority.insert(random.nextInt(100));
}
// 遍历
for(int i=0;i<10;i++){
System.out.println(priority.remove());
}
}
}
Java优先级队列简单实现
最新推荐文章于 2025-05-15 00:40:07 发布