forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStoogeSort.java
More file actions
51 lines (42 loc) · 1.53 KB
/
StoogeSort.java
File metadata and controls
51 lines (42 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.thealgorithms.sorts;
/**
* @author Amir Hassan (https://github.com/ahsNT)
* @see SortAlgorithm
*/
public class StoogeSort implements SortAlgorithm {
@Override
public <T extends Comparable<T>> T[] sort(T[] unsortedArray) {
sort(unsortedArray, 0, unsortedArray.length);
return unsortedArray;
}
public <T extends Comparable<T>> T[] sort(T[] unsortedArray, int start, int end) {
if (SortUtils.less(unsortedArray[end - 1], unsortedArray[start])) {
T temp = unsortedArray[start];
unsortedArray[start] = unsortedArray[end - 1];
unsortedArray[end - 1] = temp;
}
int len = end - start;
if (len > 2) {
int third = len / 3;
sort(unsortedArray, start, end - third);
sort(unsortedArray, start + third, end);
sort(unsortedArray, start, end - third);
}
return unsortedArray;
}
public static void main(String[] args) {
StoogeSort stoogeSort = new StoogeSort();
Integer[] integerArray = {8, 84, 53, 953, 64, 2, 202};
// Print integerArray unsorted
SortUtils.print(integerArray);
stoogeSort.sort(integerArray);
// Print integerArray sorted
SortUtils.print(integerArray);
String[] stringArray = {"g", "d", "a", "b", "f", "c", "e"};
// Print stringArray unsorted
SortUtils.print(stringArray);
stoogeSort.sort(stringArray);
// Print stringArray sorted
SortUtils.print(stringArray);
}
}