-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
63 lines (50 loc) · 1.65 KB
/
HeapSort.java
File metadata and controls
63 lines (50 loc) · 1.65 KB
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
public class HeapSort {
public static void main(String[] args) {
String[] dataset;
dataset = Util.prepareDataset(Util.getDataSetDirectoryLocation());
Util.analyzeDataset(new HeapSorter(), dataset);
}
public static class HeapSorter extends Sorter {
@Override
public void sort(Integer[] A) {
int heapSize = A.length - 1;
buildMaxHeap(A);
for (int i = A.length - 1; i > 0; i--) {
Util.swap(A, 0, i);
heapSize--;
maxHeapify(A, 0, heapSize);
}
}
private void buildMaxHeap(Integer[] A) {
int heapSize = A.length - 1;
for (int i = heapSize / 2; i >= 0; i--) {
maxHeapify(A, i, heapSize);
}
}
private void maxHeapify(Integer[] A, int i, int heapSize) {
int L = leftChild(i);
int R = rightChild(i);
int largest = i;
if (L <= heapSize) {
super.incrementComparisons(1);
if (A[L] > A[i])
largest = L;
}
if (R <= heapSize) {
super.incrementComparisons(1);
if (A[R] > A[largest])
largest = R;
}
if (largest != i) {
Util.swap(A, i, largest);
maxHeapify(A, largest, heapSize);
}
}
private int leftChild(int i) {
return 2 * i + 1;
}
private int rightChild(int i) {
return 2 * i + 2;
}
}
}