Skip to content

Commit e8cbbce

Browse files
authored
add stooge sort (#774)
1 parent 6d6b06e commit e8cbbce

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

sort/sorts_test.go

+8
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

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
func innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T {
16+
if arr[i] > arr[j] {
17+
arr[i], arr[j] = arr[j], arr[i]
18+
}
19+
if (j - i + 1) > 2 {
20+
t := int32(math.Floor(float64(j-i+1) / 3.0))
21+
arr = innerStooge(arr, i, j-t)
22+
arr = innerStooge(arr, i+t, j)
23+
arr = innerStooge(arr, i, j-t)
24+
}
25+
return arr
26+
}
27+
28+
func Stooge[T constraints.Ordered](arr []T) []T {
29+
if len(arr) == 0 {
30+
return arr
31+
}
32+
33+
return innerStooge(arr, 0, int32(len(arr)-1))
34+
}

0 commit comments

Comments
 (0)