1 public class PriQueue { 2 private static final int DEFAULT_SIZE = 10; 3 private int[] Q; 4 private int qsize; 5 private int top = -1; 6 7 public PriQueue() { 8 qsize = DEFAULT_SIZE; 9 Q = new int[qsize]; 10 } 11 12 public PriQueue(int qsize) { 13 this.qsize = qsize; 14 Q = new int[qsize]; 15 } 16 17 public boolean isEmpty() { 18 return top < 0; 19 } 20 21 public void push(int item) { 22 if (top >= qsize - 1) { 23 System.out.println("Queue is full"); 24 return; 25 } 26 Q[++top] = item; 27 riseStack(Q, top); 28 } 29 30 public int pop() { 31 if (top < 0) { 32 System.out.println("Queue is empty"); 33 return Integer.MIN_VALUE; 34 } 35 36 int retVal = Q[0]; 37 Q[0] = Q[top--]; 38 sinkStack(Q, 0, top + 1); 39 return retVal; 40 } 41 42 @Override 43 public String toString() { 44 if (top < 0) 45 return new String("[]"); 46 47 StringBuilder strb = new StringBuilder("["); 48 int i = 0; 49 for (; i < top; i++) { 50 strb.append(Q[i] + ","); 51 } 52 strb.append(Q[i] + "]"); 53 54 return strb.toString(); 55 } 56 57 58 private void riseStack(int[] arr, int index) { 59 int parent = (index - 1) / 2; 60 int temp = arr[index]; 61 while (index != 0) { 62 if (temp > arr[parent]) { 63 arr[index] = arr[parent]; 64 index = parent; 65 parent = (index - 1) / 2; 66 } else 67 break; 68 } 69 arr[index] = temp; 70 } 71 72 private void sinkStack(int[] arr, int index, int stackSize) { 73 int left = 2 * index + 1; 74 int pValue = arr[index]; 75 while (left < stackSize) { 76 if (left + 1 < stackSize) 77 left = arr[left] > arr[left + 1] ? left : left + 1; 78 if (arr[left] > pValue) { 79 arr[index] = arr[left]; 80 index = left; 81 left = 2 * index + 1; 82 } else 83 break; 84 } 85 arr[index] = pValue; 86 } 87 }