Skip to content

Commit 308bdcf

Browse files
alxkmAlex Klymenko
and
Alex Klymenko
authored
Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods (#5246)
* Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods * Rename parameter unsorted to array --------- Co-authored-by: Alex Klymenko <[email protected]>
1 parent e8f1990 commit 308bdcf

File tree

1 file changed

+16
-25
lines changed

1 file changed

+16
-25
lines changed

src/main/java/com/thealgorithms/sorts/HeapSort.java

+16-25
Original file line numberDiff line numberDiff line change
@@ -9,48 +9,39 @@ public class HeapSort implements SortAlgorithm {
99

1010
/**
1111
* 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.
1515
*/
1616
@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);
2020
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);
2324
}
24-
return unsorted;
25+
return array;
2526
}
2627

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) {
2829
for (int k = n / 2; k >= 1; k--) {
29-
siftDown(unsorted, k, n);
30+
siftDown(array, k, n);
3031
}
3132
}
3233

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) {
3435
while (2 * k <= n) {
3536
int j = 2 * k;
36-
if (j < n && less(unsorted, j, j + 1)) {
37+
if (j < n && SortUtils.less(array[j - 1], array[j])) {
3738
j++;
3839
}
39-
if (!less(unsorted, k, j)) {
40+
if (!SortUtils.less(array[k - 1], array[j - 1])) {
4041
break;
4142
}
42-
swap(unsorted, k, j);
43+
SortUtils.swap(array, k - 1, j - 1);
4344
k = j;
4445
}
4546
}
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-
}
5647
}

0 commit comments

Comments
 (0)