//冒泡 func main() { a := [...]int{3, 7, 8, 9, 1} length := len(a) var temp int for i := 0; i < length; i++ { for j := 0; j < length-1; j++ { if a[j] > a[j+1] { temp = a[j] a[j] = a[j+1] a[j+1] = temp } } } fmt.Printf("a:%v len(a):%v cap(a):%v ", a, len(a), cap(a)) }
//插入排序
func main() {
a := []int{3, 7, 8, 9, 1, 1, 10, 5}
length := len(a)
var temp int
for i := 1; i < length; i++ {
j := i
temp = a[i] //当前参与排名的数字
index := -1 //需要替换的index
for {
if j == 0 {
if index >= 0 {
a[index] = temp
index = -1
}
break
}
if temp < a[j-1] {
index = j - 1 //记录替换的位置
a[index+1] = a[index] //往后移一位
} else {
j = 0
continue
}
j--
}
}
fmt.Printf("a:%v len(a):%v cap(a):%v
", a, len(a), cap(a))
}
func main() {
a := []int{3, 7, 8, 9, 1, 1, 10, 5}
length := len(a)
b := make([]int, len(a), cap(a))
copy(b, a[0:1])
var temp int
for i := 1; i < length; i++ {
j := i
temp = a[i] //当前参与排名的数字
for {
if j > 0 && temp <= b[j-1] {
b[j] = b[j-1] //往后移一位
j--
} else {
b[j] = temp
break
}
}
}
fmt.Printf("b:%v len(b):%v cap(b):%v
", b, len(b), cap(b))
}