Skip to content

Commit 7f49918

Browse files
authored
1 parent ad81d0e commit 7f49918

1 file changed

Lines changed: 51 additions & 0 deletions

File tree

Sorts/StoogeSort.java

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

0 commit comments

Comments
 (0)