-
Notifications
You must be signed in to change notification settings - Fork 0
/
HeapSort.java
44 lines (37 loc) · 1.24 KB
/
HeapSort.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
package org.gra4j.trochilus;
public class HeapSort {
public static <T extends Comparable<? super T>> void heapSort (T[] array) {
if (array == null || array.length < 2)
return;
for (int i = array.length/2 - 1; i >= 0; i--)
percDown(array, i, array.length);
for (int i = array.length - 1; i > 0; i--) {
swapReferences(array, 0, i);
percDown(array, 0, i);
}
}
private static <T extends Comparable<? super T>> void swapReferences(T[] array, int i, int i1) {
if (i == i1)
return;
T temp = array[i];
array[i] = array[i1];
array[i1] = temp;
}
private static <T extends Comparable<? super T>> void percDown(T[] array, int i, int length) {
int child;
T temp;
for (temp = array[i]; leftChild(i) < length; i = child) {
child = leftChild(i);
if (child != length-1 && array[child].compareTo(array[child + 1]) < 0)
child++;
if (temp.compareTo(array[child]) < 0)
array[i] = array[child];
else
break;
}
array[i] = temp;
}
private static int leftChild (int i) {
return 2 * i + 1;
}
}