forked from andrei-punko/java-interview-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
58 lines (46 loc) · 1.61 KB
/
Copy pathHeapSort.java
File metadata and controls
58 lines (46 loc) · 1.61 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
package by.andd3dfx.sorting;
public class HeapSort {
public static <T extends Comparable> void apply(T[] items) {
var n = items.length;
// Build heap (rearrange array)
for (var i = n / 2 - 1; i >= 0; i--) {
heapify(items, n, i);
}
// One by one extract an element from heap
for (var i = n - 1; i > 0; i--) {
// Move current root to the end
swap(items, 0, i);
// Call max heapify on the reduced heap
heapify(items, i, 0);
}
}
// Heapify a subtree rooted with node items[root].
// n is size of heap
private static <T extends Comparable> void heapify(T items[], int n, int root) {
var largest = root;
var l = 2 * root + 1;
var r = l + 1;
// If left child is larger than root
if (l < n && greaterThan(items[l], items[largest])) {
largest = l;
}
// If right child is larger than largest at this moment
if (r < n && greaterThan(items[r], items[largest])) {
largest = r;
}
// If largest is not root
if (largest != root) {
swap(items, root, largest);
// Recursively heapify the affected subtree
heapify(items, n, largest);
}
}
private static <T extends Comparable> boolean greaterThan(T a, T b) {
return a.compareTo(b) > 0;
}
private static <T> void swap(T[] items, int i, int j) {
var tmp = items[i];
items[i] = items[j];
items[j] = tmp;
}
}