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 84 85 86 87 88 89 90 91 92 93 94
| package com;
public class Heap<T extends Comparable<T>> {
private T[] items; private int heapLength;
public Heap(int capacity) { this.items = (T[]) new Comparable[capacity+1]; this.heapLength = 0; }
public void insert(T t) { items[++heapLength] = t; swim(heapLength); }
private void swim(int k) { while (k > 1) { if (items[k/2].compareTo(items[k])<0) { T temp = items[k/2]; items[k/2] = items[k]; items[k] = temp; } k = k/2; } }
public T deleteMax() { T max = items[1]; T temp = items[1]; items[1] = items[heapLength]; items[heapLength] = temp; items[heapLength] = null; heapLength--; sink(1); return max; }
private void sink(int k) { while (2*k <= heapLength) {
int max; if (2*k+1 <= heapLength) { max = items[2*k].compareTo(items[2*k+1])>0?2*k:2*k+1; } else { max = 2*k; } if (items[k].compareTo(items[max])<0) { T temp = items[k]; items[k] = items[max]; items[max] = temp; k = max; } else { break; } } }
}
|