Go 冒泡、鸡尾酒、快速、插入 排序
package main
import "fmt"
var sli = []int{1, 43, 54, 62, 21, 66, 32, 78, 36, 76, 39}
func bubbleSort(sli []int) []int {
len := len(sli)
for i := 0; i < len; i++ {
for j := 0; j < len-1; j++ {
if sli[i] < sli[j] {
sli[i], sli[j] = sli[j], sli[i]
}
}
}
return sli
}
func cocktail_sort(arr []int, len int)[]int {
var j, left int
right := len - 1
for (left < right) {
for j = left; j < right; j++{
if (arr[j] > arr[j + 1]){
arr[j], arr[j + 1] = arr[j + 1], arr[j]
}
}
right--;
for j = right; j > left; j--{
if (arr[j - 1] > arr[j]){
arr[j], arr[j - 1] = arr[j - 1], arr[j]
}
}
left++;
}
return arr
}
func quickSort(sli []int) []int {
len := len(sli)
if len <= 1 {
return sli
}
base_num := sli[0]
left_sli := []int{}
right_sli := []int{}
for i := 1; i < len; i++ {
if base_num > sli[i] {
left_sli = append(left_sli, sli[i])
} else {
right_sli = append(right_sli, sli[i])
}
}
left_sli = quickSort(left_sli)
right_sli = quickSort(right_sli)
left_sli = append(left_sli, base_num)
return append(left_sli, right_sli...)
}
func insertSort(sli []int) []int {
len := len(sli)
for i := 0; i < len; i++ {
tmp := sli[i]
for j := i - 1; j >= 0; j-- {
if tmp < sli[j] {
sli[j+1], sli[j] = sli[j], tmp
} else {
break
}
}
}
return sli
}
func main() {
res := insertSort(sli)
fmt.Println(res)
}