Skip to content
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
39 changes: 39 additions & 0 deletions sort/oddevensort.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// oddevensort.go
// Implementation of Odd-Even Sort (Brick Sort)
// Reference: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort

package sort

import "github.com/TheAlgorithms/Go/constraints"

// OddEvenSort performs the odd-even sort algorithm on the given array.
// It is a variation of bubble sort that compares adjacent pairs, alternating
// between odd and even indexed elements in each pass until the array is sorted.
func OddEvenSort[T constraints.Ordered](arr []T) []T {
if len(arr) == 0 { // handle empty array
return arr
}

swapped := true
for swapped {
swapped = false

// Perform "odd" indexed pass
for i := 1; i < len(arr)-1; i += 2 {
if arr[i] > arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}

// Perform "even" indexed pass
for i := 0; i < len(arr)-1; i += 2 {
if arr[i] > arr[i+1] {
arr[i], arr[i+1] = arr[i+1], arr[i]
swapped = true
}
}
}

return arr
}
4 changes: 4 additions & 0 deletions sort/sorts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,10 @@ func TestCircle(t *testing.T) {
testFramework(t, sort.Circle[int])
}

func TestOddEvenSort(t *testing.T) {
testFramework(t, sort.OddEvenSort[int])
}

// END TESTS

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