# Go排序练习

1、插入排序

package main

import "fmt"

func insert(a [8]int) [8]int {
for i := 1; i < len(a); i++ {
for j := i; j > 0; j-- {
if a[j] < a[j-1] {
a[j], a[j-1] = a[j-1], a[j]
} else {
break
}
}
}
return a
}

func main() {
var i [8]int = [8]int{45, 2, 5, 68, 3, 43, 7, 9}
j := insert(i)
fmt.Println(i)
fmt.Println(j)
}

[45 2 5 68 3 43 7 9]
[2 3 5 7 9 43 45 68]

2、选择排序

package main

import "fmt"

func choose(a [8]int) [8]int {
for i := 0; i < len(a); i++ {
for j := i + 1; j < len(a); j++ {
if a[j] < a[i] {
a[i], a[j] = a[j], a[i]
}
}
}
return a
}

func main(){
var i [8]int = [8]int{45, 2, 5, 68, 3, 43, 7, 9}
j :=choose(i)    fmt.Println(i)     fmt.Println(j) } 输出： [45 2 5 68 3 43 7 9] [2 3 5 7 9 43 45 68]

3、冒泡排序

package main

import "fmt"

func bubble(a [8]int) [8]int {
for i := 0; i < len(a); i++ {
for j := 0; j < len(a)-i-1; j++ {
if a[j] > a[j+1] {
a[j], a[j+1] = a[j+1], a[j]
}
}
}
return a
}

func main() {
var i [8]int = [8]int{45, 2, 5, 68, 3, 43, 7, 9}
j := bubble(i)
fmt.Println(i)
fmt.Println(j)
}

[45 2 5 68 3 43 7 9]
[2 3 5 7 9 43 45 68]

posted @ 2019-05-22 17:42  郁冬  阅读(231)  评论(0编辑  收藏  举报