优先队列的写法有好多种,其中包括二叉树的写法,不过本人对于二叉树还没有吃透,不能随便就传授给大家,本文的方法跟前两篇目的是一样的,尽量不用第三方库,纯java数据处理。
下面是队列的属性与结构,我用键值对的方式去声明该数据的优先级:
package com.example.a;
public class Element {
private Object element; // 数据
private int priority; // 优先级
public Element(Object obj, int priority) {
this.element = obj;
this.priority = priority;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
}
下面是队列的实现,注释也很清楚:
package com.example.a;
public class PrioritySequenceQueue implements Queue {
int front = 0; // 队头
int rear = 0; // 队尾
int count = 0; // 计数器
int maxSize = 10; // 队列最大长度
Element[] queue = new Element[maxSize]; // 队列
public PrioritySequenceQueue() {
}
@Override
public void append(Object obj) throws Exception {
// TODO Auto-generated method stub
// 如果队列已满
if (count >= maxSize) {
throw new Exception("队列已满!");
}
queue[rear] = (Element) obj;
rear++;
count++;
}
@Override
public Object delete() throws Exception {
// TODO Auto-generated method stub
if (isEmpty()) {
throw new Exception("队列为空!");
}
// 默认第一个元素为优先级最高的。
Element min = queue[0];
int minIndex = 0;
for (int i = 0; i < count; i++) {
if (queue[i].getPriority() < min.getPriority()) {
min = queue[i];
minIndex = i;
}
}
// 找的优先级别最高的元素后,把该元素后面的元素向前移动。
for (int i = minIndex + 1; i < count; i++) {
queue[i - 1] = queue[i]; // 移动元素
}
rear--;
count--;
return min;
}
@Override
public Object getFront() throws Exception {
// TODO Auto-generated method stub
if (isEmpty()) {
throw new Exception("队列为空!");
}
// 默认第一个元素为优先级最高的。
Element min = queue[0];
int minIndex = 0;
for (int i = 0; i < count; i++) {
if (queue[i].getPriority() < min.getPriority()) {
min = queue[i];
minIndex = i;
}
}
return min;
}
@Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return count == 0;
}
}
下面是接口:
package com.example.a;
public interface Queue {
// 入队
public void append(Object obj) throws Exception;
// 出队
public Object delete() throws Exception;
// 获得队头元素
public Object getFront() throws Exception;
// 判断对列是否为空
public boolean isEmpty();
}
下面是测试:
package com.example.a;
public class Test {
public static void main(String[] args) throws Exception {
PrioritySequenceQueue queue = new PrioritySequenceQueue();
Element temp;
// 五个进程入队
queue.append(new Element(1, 30));
queue.append(new Element(2, 20));
queue.append(new Element(3, 40));
queue.append(new Element(4, 20));
queue.append(new Element(5, 0));
// 按照优先级出队。
System.out.println("编号 优先级");
while (!queue.isEmpty()) {
temp = (Element) queue.delete();
System.out.println(temp.getElement() + " " + temp.getPriority());
}
}
}
输出结果:
编号 优先级
5 0
2 20
4 20
1 30
3 40