排序之選擇排序
原理講解: http://www.itdecent.cn/p/fd0bf15ba55f
go代碼實現(xiàn):
package main
import (
"fmt"
)
/*
選擇排序:每一輪循環(huán)找到最小的元素,然后交換
*/
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