Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Circle Sort algorithm #730

Merged
merged 2 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions sort/circlesort.go
Original file line number Diff line number Diff line change
@@ -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
}
8 changes: 8 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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])
}
Loading