diff --git a/Sorts/SlowSort.java b/Sorts/SlowSort.java new file mode 100644 index 000000000..29f3ae0ed --- /dev/null +++ b/Sorts/SlowSort.java @@ -0,0 +1,49 @@ +package Sorts; + +/** + * @author Amir Hassan (https://github.com/ahsNT) + * @see SortAlgorithm + */ +public class SlowSort implements SortAlgorithm { + + @Override + public > T[] sort(T[] unsortedArray) { + sort(unsortedArray, 0, unsortedArray.length - 1); + return unsortedArray; + } + + private > void sort(T[] array, int i, int j) { + if (SortUtils.greaterOrEqual(i, j)) { + return; + } + int m = (i + j) / 2; + sort(array, i, m); + sort(array, m + 1, j); + if (SortUtils.less(array[j], array[m])) { + T temp = array[j]; + array[j] = array[m]; + array[m] = temp; + } + sort(array, i, j - 1); + } + + public static void main(String[] args) { + SlowSort slowSort = new SlowSort(); + + Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202, 98}; + // Print integerArray unsorted + SortUtils.print(integerArray); + + slowSort.sort(integerArray); + // Print integerArray sorted + SortUtils.print(integerArray); + + String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"}; + // Print stringArray unsorted + SortUtils.print(stringArray); + + slowSort.sort(stringArray); + // Print stringArray sorted + SortUtils.print(stringArray); + } +} diff --git a/Sorts/SortUtils.java b/Sorts/SortUtils.java index da8be334e..33be88797 100644 --- a/Sorts/SortUtils.java +++ b/Sorts/SortUtils.java @@ -46,6 +46,17 @@ final class SortUtils { return v.compareTo(w) > 0; } + /** + * This method checks if first element is greater than or equal the other element + * + * @param v first element + * @param w second element + * @return true if the first element is greater than or equal the second element + */ + static > boolean greaterOrEqual(T v, T w) { + return v.compareTo(w) >= 0; + } + /** * Prints a list *