Skip to content

Commit b94eb59

Browse files
committed
add stooge sort
1 parent 6d6b06e commit b94eb59

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

sort/sorts_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,10 @@ func TestOddEvenSort(t *testing.T) {
198198
testFramework(t, sort.OddEvenSort[int])
199199
}
200200

201+
func TestStooge(t *testing.T) {
202+
testFramework(t, sort.Stooge[int])
203+
}
204+
201205
// END TESTS
202206

203207
func benchmarkFramework(b *testing.B, f func(arr []int) []int) {
@@ -340,3 +344,7 @@ func BenchmarkTimsort(b *testing.B) {
340344
func BenchmarkCircle(b *testing.B) {
341345
benchmarkFramework(b, sort.Circle[int])
342346
}
347+
348+
func BenchmarkStooge(b *testing.B) {
349+
benchmarkFramework(b, sort.Stooge[int])
350+
}

sort/stooge_sort.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// implementation of the Stooge sort
2+
// more info at https://en.wikipedia.org/wiki/Stooge_sort
3+
// worst-case time complexity O(n^2.709511)
4+
// worst-case space complexity O(n)
5+
6+
package sort
7+
8+
import (
9+
"github.com/TheAlgorithms/Go/constraints"
10+
11+
// math imported for floor division
12+
"math"
13+
)
14+
15+
16+
func innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T {
17+
if arr[i] > arr[j] {
18+
arr[i], arr[j] = arr[j], arr[i]
19+
}
20+
if (j - i + 1) > 2 {
21+
t := int32(math.Floor(float64(j - i + 1) / 3.0))
22+
arr = innerStooge(arr, i, j-t)
23+
arr = innerStooge(arr, i+t, j)
24+
arr = innerStooge(arr, i, j-t)
25+
}
26+
return arr
27+
}
28+
29+
func Stooge[T constraints.Ordered](arr []T) []T {
30+
if len(arr) == 0 {
31+
return arr
32+
}
33+
34+
return innerStooge(arr, 0, int32(len(arr)-1))
35+
}

0 commit comments

Comments
 (0)