1 public class SimplePriorityQueue extends AbstractQueue{
2
3 static final int MAXINUM = 10;
4
5 private int[] array ;
6
7 private volatile int border = -1;
8 public SimplePriorityQueue(int[] array){
9 this.array = array;
10 }
11 public int size(){
12 return border+1;
13 }
14 public void add(int t){
15 border++;
16 if(size()>MAXINUM)
17 throw new RuntimeException();
18 if(border==0)
19 array[border] = t;
20 else{
21 shiftUp(border,t);
22 }
23 }
24 private void shiftUp(int border, int t) {
25 while (border > 0) {
26 int parent = (border - 1) >>> 1;//parentNo = (nodeNo-1)/2
27 int e = array[parent];
28 if (t<array[parent])//调用比较器的比较方法
29 break;
30 array[border] = e;
31 border = parent;
32 }
33 array[border] = t;
34 }
35 public Object poll(){
36 if(size()==0)
37 throw new RuntimeException();
38 int result = array[0];
39 border--;
40 if(size()!=0){
41 int t = array[size()];
42 shiftDonw(0,t);
43 }
44 return result;
45 }
46 private void shiftDonw(int index,int t){
47 int half = size()>>>1;
48 while(index<half){
49 int child = (index<<1) + 1;
50 int left = array[child];
51 int right = child + 1;
52 if(right<size() && left<array[right]){
53 left = array[child = right];
54 }
55 if(t>left)
56 break;
57 array[index] = left;
58 index = child;
59 }
60 array[index] = t;
61
62 }
63 @Override
64 public Object peek(){
65 if(size()==0)
66 throw new NullPointerException();
67 return array[0];
68 }
69 }
![]()
![]()
![]()
![]()
![]()