Skip to content

Commit 82b6e96

Browse files
add odd-even-sort (#762)
* add sleepsort and odd-even-sort * Delete sort/sleepsort.go * remove sleep sort from sorts_test.go
1 parent 8a1abce commit 82b6e96

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

sort/oddevensort.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// oddevensort.go
2+
// Implementation of Odd-Even Sort (Brick Sort)
3+
// Reference: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
4+
5+
package sort
6+
7+
import "github.com/TheAlgorithms/Go/constraints"
8+
9+
// OddEvenSort performs the odd-even sort algorithm on the given array.
10+
// It is a variation of bubble sort that compares adjacent pairs, alternating
11+
// between odd and even indexed elements in each pass until the array is sorted.
12+
func OddEvenSort[T constraints.Ordered](arr []T) []T {
13+
if len(arr) == 0 { // handle empty array
14+
return arr
15+
}
16+
17+
swapped := true
18+
for swapped {
19+
swapped = false
20+
21+
// Perform "odd" indexed pass
22+
for i := 1; i < len(arr)-1; i += 2 {
23+
if arr[i] > arr[i+1] {
24+
arr[i], arr[i+1] = arr[i+1], arr[i]
25+
swapped = true
26+
}
27+
}
28+
29+
// Perform "even" indexed pass
30+
for i := 0; i < len(arr)-1; i += 2 {
31+
if arr[i] > arr[i+1] {
32+
arr[i], arr[i+1] = arr[i+1], arr[i]
33+
swapped = true
34+
}
35+
}
36+
}
37+
38+
return arr
39+
}

sort/sorts_test.go

+4
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,10 @@ func TestCircle(t *testing.T) {
194194
testFramework(t, sort.Circle[int])
195195
}
196196

197+
func TestOddEvenSort(t *testing.T) {
198+
testFramework(t, sort.OddEvenSort[int])
199+
}
200+
197201
// END TESTS
198202

199203
func benchmarkFramework(b *testing.B, f func(arr []int) []int) {

0 commit comments

Comments
 (0)