Skip to content

Commit b83bb01

Browse files
authored
1 parent ee3f820 commit b83bb01

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

Sorts/SlowSort.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package Sorts;
2+
3+
/**
4+
* @author Amir Hassan (https://github.com/ahsNT)
5+
* @see SortAlgorithm
6+
*/
7+
public class SlowSort implements SortAlgorithm {
8+
9+
@Override
10+
public <T extends Comparable<T>> T[] sort(T[] unsortedArray) {
11+
sort(unsortedArray, 0, unsortedArray.length - 1);
12+
return unsortedArray;
13+
}
14+
15+
private <T extends Comparable<T>> void sort(T[] array, int i, int j) {
16+
if (SortUtils.greaterOrEqual(i, j)) {
17+
return;
18+
}
19+
int m = (i + j) / 2;
20+
sort(array, i, m);
21+
sort(array, m + 1, j);
22+
if (SortUtils.less(array[j], array[m])) {
23+
T temp = array[j];
24+
array[j] = array[m];
25+
array[m] = temp;
26+
}
27+
sort(array, i, j - 1);
28+
}
29+
30+
public static void main(String[] args) {
31+
SlowSort slowSort = new SlowSort();
32+
33+
Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202, 98};
34+
// Print integerArray unsorted
35+
SortUtils.print(integerArray);
36+
37+
slowSort.sort(integerArray);
38+
// Print integerArray sorted
39+
SortUtils.print(integerArray);
40+
41+
String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"};
42+
// Print stringArray unsorted
43+
SortUtils.print(stringArray);
44+
45+
slowSort.sort(stringArray);
46+
// Print stringArray sorted
47+
SortUtils.print(stringArray);
48+
}
49+
}

Sorts/SortUtils.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@ static <T extends Comparable<T>> boolean greater(T v, T w) {
4646
return v.compareTo(w) > 0;
4747
}
4848

49+
/**
50+
* This method checks if first element is greater than or equal the other element
51+
*
52+
* @param v first element
53+
* @param w second element
54+
* @return true if the first element is greater than or equal the second element
55+
*/
56+
static <T extends Comparable<T>> boolean greaterOrEqual(T v, T w) {
57+
return v.compareTo(w) >= 0;
58+
}
59+
4960
/**
5061
* Prints a list
5162
*

0 commit comments

Comments
 (0)