diff --git a/sort/circlesort.go b/sort/circlesort.go new file mode 100644 index 000000000..c18b0d408 --- /dev/null +++ b/sort/circlesort.go @@ -0,0 +1,44 @@ +// Package sort implements various sorting algorithms. +package sort + +import "github.com/TheAlgorithms/Go/constraints" + +// Circle sorts an array using the circle sort algorithm. +func Circle[T constraints.Ordered](arr []T) []T { + if len(arr) == 0 { + return arr + } + for doSort(arr, 0, len(arr)-1) { + } + return arr +} + +// doSort is the recursive function that implements the circle sort algorithm. +func doSort[T constraints.Ordered](arr []T, left, right int) bool { + if left == right { + return false + } + swapped := false + low := left + high := right + + for low < high { + if arr[low] > arr[high] { + arr[low], arr[high] = arr[high], arr[low] + swapped = true + } + low++ + high-- + } + + if low == high && arr[low] > arr[high+1] { + arr[low], arr[high+1] = arr[high+1], arr[low] + swapped = true + } + + mid := left + (right-left)/2 + leftHalf := doSort(arr, left, mid) + rightHalf := doSort(arr, mid+1, right) + + return swapped || leftHalf || rightHalf +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 63ca010e0..213b17e56 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -190,6 +190,10 @@ func TestTimsort(t *testing.T) { testFramework(t, sort.Timsort[int]) } +func TestCircle(t *testing.T) { + testFramework(t, sort.Circle[int]) +} + // END TESTS func benchmarkFramework(b *testing.B, f func(arr []int) []int) { @@ -328,3 +332,7 @@ func BenchmarkCycle(b *testing.B) { func BenchmarkTimsort(b *testing.B) { benchmarkFramework(b, sort.Timsort[int]) } + +func BenchmarkCircle(b *testing.B) { + benchmarkFramework(b, sort.Circle[int]) +}