Skip to content

Refactor: Replace Swap and Comparison Methods with SortUtils Utility Methods #5246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 16 additions & 25 deletions src/main/java/com/thealgorithms/sorts/HeapSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,48 +9,39 @@ public class HeapSort implements SortAlgorithm {

/**
* For simplicity, we are considering the heap root index as 1 instead of 0.
* It simplifies future calculations. Because of that we are decreasing the
* provided indexes by 1 in {@link #swap(Object[], int, int)} and
* {@link #less(Comparable[], int, int)} functions.
* This approach simplifies future calculations. As a result, we decrease
* the indexes by 1 when calling {@link SortUtils#less(Comparable, Comparable)}
* and provide adjusted values to the {@link SortUtils#swap(Object[], int, int)} methods.
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
int n = unsorted.length;
heapify(unsorted, n);
public <T extends Comparable<T>> T[] sort(T[] array) {
int n = array.length;
heapify(array, n);
while (n > 1) {
swap(unsorted, 1, n--);
siftDown(unsorted, 1, n);
SortUtils.swap(array, 0, n - 1);
n--;
siftDown(array, 1, n);
}
return unsorted;
return array;
}

private static <T extends Comparable<T>> void heapify(T[] unsorted, int n) {
private static <T extends Comparable<T>> void heapify(T[] array, int n) {
for (int k = n / 2; k >= 1; k--) {
siftDown(unsorted, k, n);
siftDown(array, k, n);
}
}

private static <T extends Comparable<T>> void siftDown(T[] unsorted, int k, int n) {
private static <T extends Comparable<T>> void siftDown(T[] array, int k, int n) {
while (2 * k <= n) {
int j = 2 * k;
if (j < n && less(unsorted, j, j + 1)) {
if (j < n && SortUtils.less(array[j - 1], array[j])) {
j++;
}
if (!less(unsorted, k, j)) {
if (!SortUtils.less(array[k - 1], array[j - 1])) {
break;
}
swap(unsorted, k, j);
SortUtils.swap(array, k - 1, j - 1);
k = j;
}
}

private static <T> void swap(T[] array, int idx, int idy) {
T swap = array[idx - 1];
array[idx - 1] = array[idy - 1];
array[idy - 1] = swap;
}

private static <T extends Comparable<T>> boolean less(T[] array, int idx, int idy) {
return array[idx - 1].compareTo(array[idy - 1]) < 0;
}
}