Skip to content

Instantly share code, notes, and snippets.

@gerep
Last active August 17, 2022 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerep/ab14e16ef578df88128f14cc0d158561 to your computer and use it in GitHub Desktop.
Save gerep/ab14e16ef578df88128f14cc0d158561 to your computer and use it in GitHub Desktop.
Selection sort algorithm
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
list := randomList(200)
// Show the list before the sort.
fmt.Println(list)
list = selectionSort(list)
// Show the sorted list.
fmt.Println(list)
}
// Generate a list of 10 random numbers from 0 to the given size.
func randomList(size int) []int {
var list = make([]int, size, size)
for i := range list {
list[i] = rand.Intn(size)
}
return list
}
func selectionSort(list []int) []int {
for current := 0; current < len(list); current++ {
minIndexFound := current
// Skip the current element and consider the remaining of the list.
for i := current + 1; i < len(list); i++ {
if list[i] < list[minIndexFound] {
minIndexFound = i
}
}
// Swap the two values, the one in the 'current' index
// with the one in the 'minIndexFound' index.
list[current], list[minIndexFound] = list[minIndexFound], list[current]
}
return list
}
@gerep
Copy link
Author

gerep commented Aug 17, 2022

On an array of length n, it performs exactly (n-1) swap instructions and exactly (n^2-n)/2 comparisons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment