-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add sleepsort and odd-even-sort * Delete sort/sleepsort.go * remove sleep sort from sorts_test.go
- Loading branch information
1 parent
8a1abce
commit 82b6e96
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters