Skip to content

Commit 32bb671

Browse files
feat: add Circle Sort algorithm (#730)
* feat: add Circle Sort algorithm * Add test and benchmark for Circle sort algorithm
1 parent ee6fef2 commit 32bb671

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

sort/circlesort.go

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Package sort implements various sorting algorithms.
2+
package sort
3+
4+
import "github.com/TheAlgorithms/Go/constraints"
5+
6+
// Circle sorts an array using the circle sort algorithm.
7+
func Circle[T constraints.Ordered](arr []T) []T {
8+
if len(arr) == 0 {
9+
return arr
10+
}
11+
for doSort(arr, 0, len(arr)-1) {
12+
}
13+
return arr
14+
}
15+
16+
// doSort is the recursive function that implements the circle sort algorithm.
17+
func doSort[T constraints.Ordered](arr []T, left, right int) bool {
18+
if left == right {
19+
return false
20+
}
21+
swapped := false
22+
low := left
23+
high := right
24+
25+
for low < high {
26+
if arr[low] > arr[high] {
27+
arr[low], arr[high] = arr[high], arr[low]
28+
swapped = true
29+
}
30+
low++
31+
high--
32+
}
33+
34+
if low == high && arr[low] > arr[high+1] {
35+
arr[low], arr[high+1] = arr[high+1], arr[low]
36+
swapped = true
37+
}
38+
39+
mid := left + (right-left)/2
40+
leftHalf := doSort(arr, left, mid)
41+
rightHalf := doSort(arr, mid+1, right)
42+
43+
return swapped || leftHalf || rightHalf
44+
}

sort/sorts_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,10 @@ func TestTimsort(t *testing.T) {
190190
testFramework(t, sort.Timsort[int])
191191
}
192192

193+
func TestCircle(t *testing.T) {
194+
testFramework(t, sort.Circle[int])
195+
}
196+
193197
// END TESTS
194198

195199
func benchmarkFramework(b *testing.B, f func(arr []int) []int) {
@@ -328,3 +332,7 @@ func BenchmarkCycle(b *testing.B) {
328332
func BenchmarkTimsort(b *testing.B) {
329333
benchmarkFramework(b, sort.Timsort[int])
330334
}
335+
336+
func BenchmarkCircle(b *testing.B) {
337+
benchmarkFramework(b, sort.Circle[int])
338+
}

0 commit comments

Comments
 (0)