1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| class PriorityQueue{ private int maxSize; //队列的长度 private long[] queueArray; //创建队列的数组的引用 private int curNum; //创建当前元素的个数 public PriorityQueue(int s) { //构造函数 this.maxSize = s; queueArray = new long[maxSize]; //创建对象 curNum = 0; //当前的元素的个数是0 } public void insert(long item){ int j; if(curNum == 0){ //输入1个数,就是1个数 queueArray[curNum++] = item; }else{ //左边是rear,右边是front,左边总比右边大 for(j=curNum-1;j>=0;j--){ //当有2个数时,若第2个数比第1个数大,则交换 if(item>queueArray[j]){ //j在-1的时候停止,rear=0,front=curNum-1 queueArray[j+1] = queueArray[j]; // 1 2 -> 1 1 -> 2 1 }else{break;} // 2 1 3 -> 2 1 1 -> 2 2 1 -> 3 2 1 } queueArray[j+1] = item; curNum++; }
} public long remove(){ return queueArray[--curNum]; } public long peekFront(){ return queueArray[curNum-1]; } public boolean isEmpty(){ return (curNum==0); } public boolean isFull(){ return (curNum==maxSize); } }
public class PriorityQueue_demo {
public static void main(String[] args) { // TODO 自动生成的方法存根 PriorityQueue queue_demo = new PriorityQueue(5); queue_demo.insert(30); queue_demo.insert(10); queue_demo.insert(50); queue_demo.insert(40); queue_demo.insert(20); while( !queue_demo.isEmpty()){ long value = queue_demo.remove(); System.out.println(value+"、"); } }
}
|