java 實現優先佇列(在插入的時候排序)
阿新 • • 發佈:2019-09-26
package helloclean.chintest; /** * 優先佇列的實現: * 實現插入的時候有序 */ public class PQueue { private int maxSize; private long[] queArray; private int nItems; public PQueue(int s) { maxSize = s; queArray = new long[maxSize]; nItems = 0; } public void insert(long item) { int j; if(nItems == 0) { queArray[nItems ++] = item; } else { for(j = nItems - 1; j >= 0; j --) { if(item > queArray[j]) { queArray[j + 1] = queArray[j]; } else { break; } } queArray[j + 1] = item; nItems ++; } } public long remove() { return queArray[-- nItems]; } public long peekMin() { return queArray[nItems - 1]; } public boolean isEmpty() { return (nItems == 0); } public boolean isFull() { return (nItems == maxSize); } }
package helloclean.chintest;
public class PQApp {
public static void main(String[] args) {
PQueue pQueue= new PQueue(5);
pQueue.insert(50);
pQueue.insert(30);
pQueue.insert(40);
pQueue.insert(20);
pQueue.insert(10);
while (!pQueue.isEmpty()) {
long item = pQueue.remove();
System.out.print(item + " ");
}
System.out.println();
}
}