-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeap.java
57 lines (48 loc) · 1.09 KB
/
Heap.java
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
package com.com.immoc.nfx;
/**
* Created by feixiang.nfx on 2017/7/30.
*/
public class HeapSort {
private int[] data;
private int count;
private void exch(int a, int b) {
int tmp = data[a];
data[a] = data[b];
data[b] = tmp;
}
private void swim(int k) {
while (k > 1 && data[k / 2] < data[k]) {
exch(k / 2, k);
k = k / 2;
}
}
private void sink(int k) {
while (2 * k <= count) {
int j = 2 * k;
if (j + 1 <= count && data[j] < data[j + 1]) j++;
if (data[j] <= data[k]) break;
exch(k,j);
k = j;
}
}
public int size() {
return count;
}
public HeapSort(int capacity) {
data = new int[capacity + 1];
count = 0;
}
public boolean isEmpty() {
return count == 0;
}
public void insert(int item) {
data[++count] = item;
swim(count);
}
public int extractMax() {
int ret = data[1];
exch(1, count--);
sink(1);
return ret;
}
}