Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Sorts/StoogeSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Stooge Sort sorts an array based on divide and conquer principle
* note the exceptionally bad time complexity
* more information: https://en.wikipedia.org/wiki/Stooge_sort
*
*/
export function stoogeSort (items, leftEnd, rightEnd) {
if (items[rightEnd - 1] < items[leftEnd]) {
const temp = items[leftEnd]
items[leftEnd] = items[rightEnd - 1]
items[rightEnd - 1] = temp
}
const length = rightEnd - leftEnd
if (length > 2) {
const third = Math.floor(length / 3)
stoogeSort(items, leftEnd, rightEnd - third)
stoogeSort(items, leftEnd + third, rightEnd)
stoogeSort(items, leftEnd, rightEnd - third)
}
return items
}
31 changes: 31 additions & 0 deletions Sorts/test/StoogeSort.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { stoogeSort } from '../StoogeSort'

test('The StoogeSort of the array [1, 6, 4, 7, 2] is [1, 2, 4, 6, 7]', () => {
const arr = [1, 6, 4, 7, 2]
const res = stoogeSort(arr, 0, arr.length)
expect(res).toEqual([1, 2, 4, 6, 7])
})

test('The StoogeSort of the array [] is []', () => {
const arr = []
const res = stoogeSort(arr, 0, arr.length)
expect(res).toEqual([])
})

test('The StoogeSort of the array [46, 15, 49, 65, 23] is [15, 23, 46, 49, 65]', () => {
const arr = [46, 15, 49, 65, 23]
const res = stoogeSort(arr, 0, arr.length)
expect(res).toEqual([15, 23, 46, 49, 65])
})

test('The StoogeSort of the array [136, 459, 132, 566, 465] is [132, 136, 459, 465, 566]', () => {
const arr = [136, 459, 132, 566, 465]
const res = stoogeSort(arr, 0, arr.length)
expect(res).toEqual([132, 136, 459, 465, 566])
})

test('The StoogeSort of the array [45, 3, 156, 1, 56] is [1, 3, 45, 56, 156]', () => {
const arr = [45, 3, 156, 1, 56]
const res = stoogeSort(arr, 0, arr.length)
expect(res).toEqual([1, 3, 45, 56, 156])
})