Skip to content

Commit

Permalink
add stooge sort
Browse files Browse the repository at this point in the history
  • Loading branch information
lyqio committed Jan 12, 2025
1 parent 6d6b06e commit 5c5db93
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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])
}
34 changes: 34 additions & 0 deletions sort/stooge_sort.go
Original file line number Diff line number Diff line change
@@ -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))
}

0 comments on commit 5c5db93

Please sign in to comment.