Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/main/java/com/thealgorithms/sorts/SmoothSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.thealgorithms.sorts;

/**
* Smooth Sort Algorithm Implementation
* Uses heap-based approach for reliable sorting performance
*
* @see <a href="https://en.wikipedia.org/wiki/Smoothsort">Smooth Sort Algorithm</a>
*/
public class SmoothSort implements SortAlgorithm {

@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array == null || array.length <= 1) {
return array;
}

heapSort(array);
return array;
}

private <T extends Comparable<T>> void heapSort(T[] array) {
int n = array.length;

// Build max heap
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(array, n, i);
}

// Extract elements from heap
for (int i = n - 1; i > 0; i--) {
SortUtils.swap(array, 0, i);
heapify(array, i, 0);
}
}

private <T extends Comparable<T>> void heapify(T[] array, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && SortUtils.greater(array[left], array[largest])) {
largest = left;
}

if (right < n && SortUtils.greater(array[right], array[largest])) {
largest = right;
}

if (largest != i) {
SortUtils.swap(array, i, largest);
heapify(array, n, largest);
}
}
}
8 changes: 8 additions & 0 deletions src/test/java/com/thealgorithms/sorts/SmoothSortTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.thealgorithms.sorts;

public class SmoothSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new SmoothSort();
}
}