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 <alx@alx.com>
This commit is contained in:
parent
e8f1990c8c
commit
308bdcfc19
@ -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;
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user