-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
62 lines (54 loc) · 1.14 KB
/
Copy pathHeapSort.java
File metadata and controls
62 lines (54 loc) · 1.14 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
/**
*
* @author KAKANAKOU MIGUEL
*
*/
public final class HeapSort {
/**
* Use the shell sort method to sort the given array A
*
* @param A Array of Comparable that contains the object to sort
*/
public static void sort(Comparable[] A) {
if (A == null)
return;
heapify(A);
for (int k = A.length; k >= 1; k--) {
exch(A, 1, k);
sink(A, 1, k - 1);
}
}
private static void heapify(Comparable[] A) {
for (int k = A.length / 2; k >= 1; k--)
sink(A, k, A.length);
}
private static void sink(Comparable[] A, int indice, int len) {
int j;
while (indice <= len / 2) {
j = 2 * indice;
if ((j < len) && (less(A, j, j + 1)))
j++;
if (!less(A, indice, j))
break;
exch(A, indice, j);
indice = j;
}
}
private static void exch(Comparable[] A, int i, int j) {
i = getArrayIndex(i);
j = getArrayIndex(j);
Comparable k = A[i];
A[i] = A[j];
A[j] = k;
}
private static boolean less(Comparable[] A, int i, int j) {
i = getArrayIndex(i);
j = getArrayIndex(j);
if (A[i].compareTo(A[j]) < 0)
return true;
return false;
}
private static int getArrayIndex(int indice) {
return --indice;
}
}