排序之冒泡
原理讲解: https://www.jianshu.com/p/4a06dcd45229
go代码实现:
package main
import (
"fmt"
)
func bubble_sort(a []int) {
for i := 0; i < len(a); i++ {
for j := 0; j < len(a) - i -1; j++ {
if a[j] > a[j+1] {
temp := a[j]
a[j] = a[j+1]
a[j+1] = temp
}
}
}
}
func main() {
a := []int{1,3,5,2,1}
fmt.Println(a)
bubble_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_bubble_sort_go.exe F:/code/test/bubble_sort/bubble_sort.go #gosetup
C:\Users\windows10\AppData\Local\Temp\___go_build_bubble_sort_go.exe #gosetup
[1 3 5 2 1]
[1 1 2 3 5]
Process finished with exit code 0