|
| 1 | +public class Heap<Key extends Comparable<Key>> { |
| 2 | + private Key[] data; |
| 3 | + private int capacity; |
| 4 | + private int count; |
| 5 | + private boolean isMax; |
| 6 | + |
| 7 | + public int size() { |
| 8 | + return count; |
| 9 | + } |
| 10 | + |
| 11 | + public boolean isEmpty() { |
| 12 | + return count == 0; |
| 13 | + } |
| 14 | + |
| 15 | + public Heap(int capacity, boolean isMax) { |
| 16 | + data = (Key[]) new Comparable[capacity + 1]; |
| 17 | + count = 0; |
| 18 | + this.capacity = capacity; |
| 19 | + this.isMax = isMax; |
| 20 | + } |
| 21 | + |
| 22 | + private boolean less(int i, int j) { |
| 23 | + return data[i].compareTo(data[j]) < 0; |
| 24 | + } |
| 25 | + |
| 26 | + private void exch(int i, int j) { |
| 27 | + Key tmp = data[i]; |
| 28 | + data[i] = data[j]; |
| 29 | + data[j] = tmp; |
| 30 | + } |
| 31 | + |
| 32 | + private boolean needExch(int i, int j) { |
| 33 | + return (isMax ? less(i, j) : less(j, i)); |
| 34 | + } |
| 35 | + |
| 36 | + public void swin(int k) { |
| 37 | + while (k > 1 && needExch(k / 2, k)) { |
| 38 | + exch(k / 2, k); |
| 39 | + k = k / 2; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public void sink(int k) { |
| 44 | + while (k * 2 <= count) { |
| 45 | + int j = k * 2; |
| 46 | + if (j < count && needExch(j, j + 1)) j++; |
| 47 | + if (!needExch(k, j)) break; |
| 48 | + exch(k, j); |
| 49 | + k = j; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public void insert(Key key) { |
| 54 | + data[++count] = key; |
| 55 | + swin(count); |
| 56 | + } |
| 57 | + |
| 58 | + public Key delMax() { |
| 59 | + Key key = data[1]; |
| 60 | + exch(1, count); |
| 61 | + data[count--] = null; |
| 62 | + sink(1); |
| 63 | + return key; |
| 64 | + } |
| 65 | + |
| 66 | + private void sort(Comparable a[]) { |
| 67 | + |
| 68 | + } |
| 69 | + |
| 70 | + public static void main(String[] args) { |
| 71 | + int[] nums = {2, 3, 4, 5, 6}; |
| 72 | + Heap<Integer> maxHeap = new Heap<>(nums.length, false); |
| 73 | + for (int i = 0; i < nums.length; i++) { |
| 74 | + maxHeap.insert(nums[i]); |
| 75 | + } |
| 76 | + for (int i = 0; i < nums.length; i++) { |
| 77 | + System.out.println(maxHeap.delMax()); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments