diff --git a/sort/oddevensort.go b/sort/oddevensort.go new file mode 100644 index 000000000..5e98ef409 --- /dev/null +++ b/sort/oddevensort.go @@ -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 +} diff --git a/sort/sorts_test.go b/sort/sorts_test.go index 213b17e56..a04f19eb0 100644 --- a/sort/sorts_test.go +++ b/sort/sorts_test.go @@ -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) {