diff --git a/sort/sorts_test.go b/sort/sorts_test.go index a04f19eb0..f2394c334 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -198,6 +198,10 @@ func TestOddEvenSort(t *testing.T) { testFramework(t, sort.OddEvenSort[int]) } +func TestStooge(t *testing.T) { + testFramework(t, sort.Stooge[int]) +} + // END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -340,3 +344,7 @@ func BenchmarkTimsort(b *testing.B) { func BenchmarkCircle(b *testing.B) { benchmarkFramework(b, sort.Circle[int]) } + +func BenchmarkStooge(b *testing.B) { + benchmarkFramework(b, sort.Stooge[int]) +} diff --git a/sort/stooge_sort.go b/sort/stooge_sort.go new file mode 100644 index 000000000..45d2206c4 --- /dev/null +++ b/sort/stooge_sort.go @@ -0,0 +1,34 @@ +// implementation of the Stooge sort +// more info at https://en.wikipedia.org/wiki/Stooge_sort +// worst-case time complexity O(n^2.709511) +// worst-case space complexity O(n) + +package sort + +import ( + "github.com/TheAlgorithms/Go/constraints" + + // math imported for floor division + "math" +) + +func innerStooge[T constraints.Ordered](arr []T, i int32, j int32) []T { + if arr[i] > arr[j] { + arr[i], arr[j] = arr[j], arr[i] + } + if (j - i + 1) > 2 { + t := int32(math.Floor(float64(j-i+1) / 3.0)) + arr = innerStooge(arr, i, j-t) + arr = innerStooge(arr, i+t, j) + arr = innerStooge(arr, i, j-t) + } + return arr +} + +func Stooge[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { + return arr + } + + return innerStooge(arr, 0, int32(len(arr)-1)) +}