Selection sort is a simple sorting algorithm that repeatedly selects the minimum item from the unsorted part of the list and swaps it with the first unsorted item.
Example code in Go:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
r := bufio.NewReader(os.Stdin)
strInput, _ := r.ReadString('\n')
strInput = strings.TrimSpace(strInput)
strSlice := strings.Split(strInput, " ")
var nums []int
for _, v := range strSlice {
num, _ := strconv.Atoi(v)
nums = append(nums, num)
}
// Selection Sort
// 1) go through slice and find lowest value
// 2) put lowest value at the beginning of slice by swapping with current one
for i := 0; i < len(nums); i++ {
minIndex := i
for j := i; j < len(nums); j++ {
if nums[j] < nums[minIndex] {
minIndex = j
}
}
nums[i], nums[minIndex] = nums[minIndex], nums[i]
}
fmt.Println(nums)
}
Ok, lets go!
- For each iteration of the outer loop (
for i...), the inner loop (for j...) goes over the unsorted part of the fragmentnums, starting from the current indexiand ending with the end of the slice. - Variable
jserves as an index of the current iteration in the inner loop, where we check if the value atnums[j]is less than the value at the current minimum indexnums[minIndex]. - If
nums[j]is less, we update minIndex to the value ofj, noting the new minimum value. - After the end of the inner loop, the outer loop changes the value by the current index
ito the value by the minimal indexnums[minIndex], placing the minimal value in the sorted part of the fragmentnumsat positioni.