Created
May 10, 2021 20:58
-
-
Save kiambogo/6587d6f012b07254c5a8e4dc458dce9d to your computer and use it in GitHub Desktop.
Go Selection Sort
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
package main | |
import ( | |
"log" | |
"math" | |
) | |
func main() { | |
array := []int{} | |
selectionSort(&array) | |
assert([]int{}, array) | |
array = []int{1} | |
selectionSort(&array) | |
assert([]int{1}, array) | |
array = []int{1, 2} | |
selectionSort(&array) | |
assert([]int{1, 2}, array) | |
array = []int{3, 1, 2} | |
selectionSort(&array) | |
assert([]int{1, 2, 3}, array) | |
array = []int{3, 2, 1, 4} | |
selectionSort(&array) | |
assert([]int{1, 2, 3, 4}, array) | |
} | |
func selectionSort(arr *[]int) { | |
if len(*arr) <= 1 { | |
return | |
} | |
for i := range *arr { | |
min := math.MaxInt32 | |
minIndex := 0 | |
for j, v := range (*arr)[i:] { | |
if v <= min { | |
min = v | |
minIndex = i + j | |
} | |
} | |
(*arr)[minIndex] = (*arr)[i] | |
(*arr)[i] = min | |
} | |
return | |
} | |
func assert(expected, actual []int) { | |
if len(expected) != len(actual) { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
for x := range expected { | |
if expected[x] != actual[x] { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment