PriorityQueue
<Introduction to algorithm>
A priority queue is a data structure for maintaining a set S of elements, each
with an associated value called a key. A max-priority queue supports the following
operations:
INSERT.S; x/ inserts the element x into the set S, which is equivalent to the operation
MAXIMUM.S/ returns the element of S with the largest key.
EXTRACT-MAX.S/ removes and returns the element of S with the largest key.
INCREASE-KEY.S; x; k/ increases the value of element x’s key to the new value k,
which is assumed to be at least as large as x’s current key value.
1 public class PriorityQueue { 2 3 private final int DEFAULT_CAPACITY_VALUE=16; 4 private int[] queue=new int[DEFAULT_CAPACITY_VALUE]; 5 private int heapSize=0; 6 7 public void insert(int value){ 8 queue[heapSize++]=value; 9 increaseKey(heapSize, value); 10 } 11 12 public void increaseKey(int heapIndex,int newValue){ 13 if(newValue < queue[heapIndex-1]){ 14 System.out.println("new key is smaller than current key"); 15 } 16 queue[heapIndex-1]=newValue; 17 int parentIndex=heapIndex/2; 18 while(heapIndex>1 && queue[parentIndex-1]<newValue){ 19 int temp=queue[parentIndex-1]; 20 queue[parentIndex-1]=newValue; 21 queue[heapIndex-1]=temp; 22 heapIndex=parentIndex; 23 parentIndex=parentIndex/2; 24 } 25 } 26 27 public int maximum(){ 28 return queue[0]; 29 } 30 31 public int extractMax(){ 32 if(heapSize<1){ 33 System.out.println("heap underflow"); 34 return -1; 35 } 36 int max=queue[0]; 37 queue[0]=queue[heapSize-1]; 38 heapSize--; 39 maxHeapify(queue, 1); 40 return max; 41 } 42 43 public void maxHeapify(int[] a,int index){ 44 int l=index*2; 45 int r=l+1; 46 int largest; 47 if(l<=heapSize && a[l-1]>a[index-1]){ 48 largest=l; 49 } 50 else{ 51 largest=index; 52 } 53 if(r<=heapSize && a[r-1]>a[largest-1]){ 54 largest=r; 55 } 56 if(largest != index){ 57 int temp=a[index-1]; 58 a[index-1]=a[largest-1]; 59 a[largest-1]=temp; 60 maxHeapify(a,largest); 61 } 62 63 } 64 65 public static void main(String[] args) { 66 // TODO Auto-generated method stub 67 PriorityQueue q=new PriorityQueue(); 68 q.insert(2); 69 q.insert(6); 70 q.insert(3); 71 q.insert(8); 72 q.insert(7); 73 q.insert(9); 74 System.out.println(q.extractMax()); 75 System.out.println(q.extractMax()); 76 q.insert(9); 77 q.insert(1); 78 q.insert(10); 79 System.out.println(q.extractMax()); 80 System.out.println(q.extractMax()); 81 82 } 83 84 }
浙公网安备 33010602011771号