Skip to content

Commit

Permalink
add odd-even-sort (#762)
Browse files Browse the repository at this point in the history
* add sleepsort and odd-even-sort

* Delete sort/sleepsort.go

* remove sleep sort from sorts_test.go
  • Loading branch information
SimonWaldherr authored Nov 27, 2024
1 parent 8a1abce commit 82b6e96
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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

0 comments on commit 82b6e96

Please sign in to comment.