Add Slow Sort (#2546) (#2547)

This commit is contained in:
Amir
2021-10-13 06:54:55 +02:00
committed by GitHub
parent ee3f82007a
commit b83bb0178d
2 changed files with 60 additions and 0 deletions

49
Sorts/SlowSort.java Normal file
View File

@ -0,0 +1,49 @@
package Sorts;
/**
* @author Amir Hassan (https://github.com/ahsNT)
* @see SortAlgorithm
*/
public class SlowSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> T[] sort(T[] unsortedArray) {
sort(unsortedArray, 0, unsortedArray.length - 1);
return unsortedArray;
}
private <T extends Comparable<T>> 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);
}
}

View File

@ -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 <T extends Comparable<T>> boolean greaterOrEqual(T v, T w) {
return v.compareTo(w) >= 0;
}
/**
* Prints a list
*