A Go implementation of selection sorting
package main
import "fmt"
Swap len(arr) -n for the NTH time
func selectSort(arr *[5]int){
for j := 0; j < len(arr) - 1; j++ { Len (arr) -1
// Assume the first element has the largest value (descending sort)
max := arr[j]
maxIndex := j
// Iterate over the following elements for comparison
for i := j + 1; i < len(arr); i++ {
if max < arr[i] {
max = arr[i] // There is no rush to swap values, just give Max the maximum
maxIndex = i
}
}
/ / exchange value
ifmaxIndex ! = j { arr[j], arr[maxIndex] = arr[maxIndex], arr[j] } fmt.Printf("%d th %v\n", j+1, *arr)
}
}
func main(a){
arr := [5]int{1.3.6.9.8}
selectSort(&arr)
}
Copy the code
Output:
1st [9 3 6 1 8] 2nd [9 8 6 1 3] 3rd [9 8 6 1 3] 4th [9 8 6 3]Copy the code