排序之选择排序
原理讲解: https://www.jianshu.com/p/fd0bf15ba55f
go代码实现:
package main
import (
"fmt"
)
/*
选择排序:每一轮循环找到最小的元素,然后交换
*/
func selection_sort(a []int) {
for i := 0; i < len(a); i++ {
index := i
for j := i + 1; j < len(a); j++ {
if a[j] < a[index] {
index = j
}
}
if index != i {
temp := a[i]
a[i] = a[index]
a[index] = temp
}
}
}
func main() {
a := []int{1,3,5,2,1}
fmt.Println(a)
selection_sort(a)
fmt.Println(a)
}
运行结果:
GOROOT=C:\Go #gosetup
GOPATH=F:\goPath #gosetup
C:\Go\bin\go.exe build -o C:\Users\windows10\AppData\Local\Temp\___go_build_selection_sort_go.exe F:/code/test/selection_sort/selection_sort.go #gosetup
C:\Users\windows10\AppData\Local\Temp\___go_build_selection_sort_go.exe #gosetup
[1 3 5 2 1]
[1 1 2 3 5]
Process finished with exit code 0