File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff 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
199203func benchmarkFramework (b * testing.B , f func (arr []int ) []int ) {
You can’t perform that action at this time.
0 commit comments