Last active
August 17, 2022 12:47
-
-
Save gerep/ab14e16ef578df88128f14cc0d158561 to your computer and use it in GitHub Desktop.
Selection sort algorithm
This file contains hidden or 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 ( | |
"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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On an array of length
n
, it performs exactly(n-1)
swap instructions and exactly(n^2-n)/2
comparisons.