Skip to content

Commit 2e18fbb

Browse files
authored
merge: Add the Stooge Sort Algorithm (TheAlgorithms#998)
* Add stooge sort sorting algorithm with included tests * Add stooge sort sorting algorithm with included tests * Add correct url for more information * Add time complexity warning
1 parent 5641b6f commit 2e18fbb

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Sorts/StoogeSort.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
* Stooge Sort sorts an array based on divide and conquer principle
3+
* note the exceptionally bad time complexity
4+
* more information: https://en.wikipedia.org/wiki/Stooge_sort
5+
*
6+
*/
7+
export function stoogeSort (items, leftEnd, rightEnd) {
8+
if (items[rightEnd - 1] < items[leftEnd]) {
9+
const temp = items[leftEnd]
10+
items[leftEnd] = items[rightEnd - 1]
11+
items[rightEnd - 1] = temp
12+
}
13+
const length = rightEnd - leftEnd
14+
if (length > 2) {
15+
const third = Math.floor(length / 3)
16+
stoogeSort(items, leftEnd, rightEnd - third)
17+
stoogeSort(items, leftEnd + third, rightEnd)
18+
stoogeSort(items, leftEnd, rightEnd - third)
19+
}
20+
return items
21+
}

Sorts/test/StoogeSort.test.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { stoogeSort } from '../StoogeSort'
2+
3+
test('The StoogeSort of the array [1, 6, 4, 7, 2] is [1, 2, 4, 6, 7]', () => {
4+
const arr = [1, 6, 4, 7, 2]
5+
const res = stoogeSort(arr, 0, arr.length)
6+
expect(res).toEqual([1, 2, 4, 6, 7])
7+
})
8+
9+
test('The StoogeSort of the array [] is []', () => {
10+
const arr = []
11+
const res = stoogeSort(arr, 0, arr.length)
12+
expect(res).toEqual([])
13+
})
14+
15+
test('The StoogeSort of the array [46, 15, 49, 65, 23] is [15, 23, 46, 49, 65]', () => {
16+
const arr = [46, 15, 49, 65, 23]
17+
const res = stoogeSort(arr, 0, arr.length)
18+
expect(res).toEqual([15, 23, 46, 49, 65])
19+
})
20+
21+
test('The StoogeSort of the array [136, 459, 132, 566, 465] is [132, 136, 459, 465, 566]', () => {
22+
const arr = [136, 459, 132, 566, 465]
23+
const res = stoogeSort(arr, 0, arr.length)
24+
expect(res).toEqual([132, 136, 459, 465, 566])
25+
})
26+
27+
test('The StoogeSort of the array [45, 3, 156, 1, 56] is [1, 3, 45, 56, 156]', () => {
28+
const arr = [45, 3, 156, 1, 56]
29+
const res = stoogeSort(arr, 0, arr.length)
30+
expect(res).toEqual([1, 3, 45, 56, 156])
31+
})

0 commit comments

Comments
 (0)