Skip to content

Commit 7281281

Browse files
committed
Added StoogeSort algorithm and JUnit Test
1 parent 08dc6ad commit 7281281

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package src.main.java.com.sorts;
2+
3+
import static src.main.java.com.sorts.SortUtils.swap;
4+
import static src.main.java.com.sorts.SortUtils.less;
5+
6+
public class StoogeSort {
7+
8+
/**
9+
* This method implements recursion StoogeSort
10+
*
11+
* @param int[] array to store number elements
12+
* @param f first element in the array
13+
* @param l last element in the array
14+
*/
15+
public <T extends Comparable<T>> T[] sort(T[] arr, int f, int l) {
16+
17+
// Ends recursion when met
18+
if (f >= l)
19+
return arr;
20+
21+
if (less(arr[l], arr[f])) {
22+
swap(arr, f, l);
23+
}
24+
25+
if (l - f + 1 > 2) {
26+
int entry = (l - f + 1) / 3;
27+
28+
// Does a recursive sort of the first two thirds elements
29+
sort(arr, f, l - entry);
30+
31+
// Does a recursive sort of the last two thirds elements
32+
sort(arr, f + entry, l);
33+
34+
// Another recursive sort first two thirds elements to confirm
35+
sort(arr, f, l - entry);
36+
}
37+
return arr;
38+
}
39+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package src.test.java.com.sorts;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
import src.main.java.com.sorts.StoogeSort;
6+
7+
public class StoogeSortTest {
8+
9+
@Test
10+
public void stoogeSortTest() {
11+
StoogeSort stoogesort = new StoogeSort();
12+
13+
Integer unsortedArr[] = { 2, 4, 5, 3, 1 };
14+
Integer n = unsortedArr.length;
15+
Integer sortedArr[] = { 1, 2, 3, 4, 5 };
16+
Assert.assertArrayEquals(sortedArr, stoogesort.sort(unsortedArr, 0, n - 1));
17+
18+
unsortedArr = new Integer[] { -22, -34, -25, -53, -11 };
19+
sortedArr = new Integer[] { -53, -34, -25, -22, -11 };
20+
Assert.assertArrayEquals(sortedArr, stoogesort.sort(unsortedArr, 0, n - 1));
21+
22+
Character[] unsortedCharArr = new Character[] { 'a', 'r', 'd', 'k', 'p' };
23+
n = unsortedCharArr.length;
24+
Character[] sortedCharArr = new Character[] { 'a', 'd', 'k', 'p', 'r' };
25+
Assert.assertArrayEquals(sortedCharArr, stoogesort.sort(unsortedCharArr, 0, n - 1));
26+
}
27+
}

0 commit comments

Comments
 (0)