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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
| public class Heap { private int[] data;
public Heap(int[] data) { this.data = data; buildHeap(); }
private void buildHeap() { for (int i = (data.length) / 2 - 1; i >= 0; i--) { heapify(i, data.length); } }
private void heapify(int i, int length) { int l = left(i); int r = right(i);
int smallest = i; if (l < length && data[l] < data[smallest]) smallest = l; if (r < length && data[r] < data[smallest]) smallest = r; if (i == smallest) return; swap(i, smallest); heapify(smallest, length); }
public void sort() { for (int i = data.length - 1; i >= 0; i--) { swap(i, 0); heapify(0, i); } }
private int right(int i) { return (i + 1) << 1; }
private int left(int i) { return ((i + 1) << 1) - 1; }
private void swap(int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; }
public int getRoot() { return data[0]; }
public void setRoot(int root) { data[0] = root; heapify(0, data.length); } }
public class HeapDemo { public static void main(String[] args) { int[] data = {1, 6, 3, 4, 5, 2, 8, 9, 7, 10};
int[] top5 = topK(data, 5);
for (int i = 0; i < top5.length; i++) { System.out.println(top5[i]); } }
private static int[] topK(int[] data, int k) { int[] topk = new int[k]; for (int i = 0; i < k; i++) { topk[i] = data[i]; }
Heap heap = new Heap(topk);
for (int i = k; i < data.length; i++) { heap.sort(); int root = heap.getRoot();
if (data[i] > root) { heap.setRoot(data[i]); } } return topk; } }
|