@@ -9,48 +9,39 @@ public class HeapSort implements SortAlgorithm {
9
9
10
10
/**
11
11
* For simplicity, we are considering the heap root index as 1 instead of 0.
12
- * It simplifies future calculations. Because of that we are decreasing the
13
- * provided indexes by 1 in {@link #swap(Object[], int, int)} and
14
- * {@link #less(Comparable [], int, int)} functions .
12
+ * This approach simplifies future calculations. As a result, we decrease
13
+ * the indexes by 1 when calling {@link SortUtils#less(Comparable, Comparable)}
14
+ * and provide adjusted values to the {@link SortUtils#swap(Object [], int, int)} methods .
15
15
*/
16
16
@ Override
17
- public <T extends Comparable <T >> T [] sort (T [] unsorted ) {
18
- int n = unsorted .length ;
19
- heapify (unsorted , n );
17
+ public <T extends Comparable <T >> T [] sort (T [] array ) {
18
+ int n = array .length ;
19
+ heapify (array , n );
20
20
while (n > 1 ) {
21
- swap (unsorted , 1 , n --);
22
- siftDown (unsorted , 1 , n );
21
+ SortUtils .swap (array , 0 , n - 1 );
22
+ n --;
23
+ siftDown (array , 1 , n );
23
24
}
24
- return unsorted ;
25
+ return array ;
25
26
}
26
27
27
- private static <T extends Comparable <T >> void heapify (T [] unsorted , int n ) {
28
+ private static <T extends Comparable <T >> void heapify (T [] array , int n ) {
28
29
for (int k = n / 2 ; k >= 1 ; k --) {
29
- siftDown (unsorted , k , n );
30
+ siftDown (array , k , n );
30
31
}
31
32
}
32
33
33
- private static <T extends Comparable <T >> void siftDown (T [] unsorted , int k , int n ) {
34
+ private static <T extends Comparable <T >> void siftDown (T [] array , int k , int n ) {
34
35
while (2 * k <= n ) {
35
36
int j = 2 * k ;
36
- if (j < n && less (unsorted , j , j + 1 )) {
37
+ if (j < n && SortUtils . less (array [ j - 1 ], array [ j ] )) {
37
38
j ++;
38
39
}
39
- if (!less (unsorted , k , j )) {
40
+ if (!SortUtils . less (array [ k - 1 ], array [ j - 1 ] )) {
40
41
break ;
41
42
}
42
- swap (unsorted , k , j );
43
+ SortUtils . swap (array , k - 1 , j - 1 );
43
44
k = j ;
44
45
}
45
46
}
46
-
47
- private static <T > void swap (T [] array , int idx , int idy ) {
48
- T swap = array [idx - 1 ];
49
- array [idx - 1 ] = array [idy - 1 ];
50
- array [idy - 1 ] = swap ;
51
- }
52
-
53
- private static <T extends Comparable <T >> boolean less (T [] array , int idx , int idy ) {
54
- return array [idx - 1 ].compareTo (array [idy - 1 ]) < 0 ;
55
- }
56
47
}
0 commit comments