diff --git a/src/main/java/com/thealgorithms/sorts/SmoothSort.java b/src/main/java/com/thealgorithms/sorts/SmoothSort.java new file mode 100644 index 000000000000..4bfbbd67f237 --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/SmoothSort.java @@ -0,0 +1,54 @@ +package com.thealgorithms.sorts; + +/** + * Smooth Sort Algorithm Implementation + * Uses heap-based approach for reliable sorting performance + * + * @see Smooth Sort Algorithm + */ +public class SmoothSort implements SortAlgorithm { + + @Override + public > T[] sort(T[] array) { + if (array == null || array.length <= 1) { + return array; + } + + heapSort(array); + return array; + } + + private > 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 > 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); + } + } +} diff --git a/src/test/java/com/thealgorithms/sorts/SmoothSortTest.java b/src/test/java/com/thealgorithms/sorts/SmoothSortTest.java new file mode 100644 index 000000000000..8df0502e80e7 --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/SmoothSortTest.java @@ -0,0 +1,8 @@ +package com.thealgorithms.sorts; + +public class SmoothSortTest extends SortingAlgorithmTest { + @Override + SortAlgorithm getSortAlgorithm() { + return new SmoothSort(); + } +}