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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| package com;
public class MaxPriorityQueue<T extends Comparable<T>> {
private T[] data; private int maxPriorityQueueLength;
MaxPriorityQueue(int capacity) { this.data = (T[]) new Comparable[capacity+1]; }
public int size() { return maxPriorityQueueLength; }
public boolean isEmpty() { return maxPriorityQueueLength==0; }
private boolean less(int i, int j){ return data[i].compareTo(data[j])<0; }
private void exch(int i, int j) { T tmp = data[i]; data[i] = data[j]; data[j] = tmp; }
public void insert(T t) { data[++maxPriorityQueueLength] = t; swim(maxPriorityQueueLength); }
public T delMax() { T max = data[1]; exch(1, maxPriorityQueueLength); maxPriorityQueueLength--; sink(1); return max; }
private void swim(int k) { while (k>1) { if (less(k/2, k)) { exch(k/2, k); } k = k/2; } }
private void sink(int k) { while (2*k<maxPriorityQueueLength) { int max; if (2*k+1<=maxPriorityQueueLength) { if (less(2*k, 2*k+1)) { max = 2*k+1; } else { max = 2*k; } } else { max = 2*k; }
if (!less(k, max)) { break; }
exch(k, max);
k = max; } }
}
|