前面我们讲解了鸡尾酒排序,今天我们来用代码实现下
package main
import "fmt"
//鸡尾酒排序
func cocktailSort(theArray[] int)[]int{
theLen := len(theArray)
for true{
flag := false
for i := 0; i < theLen-1; i++ {
if(theArray[i] > theArray[i+1]) {
theArray[i], theArray[i+1] = theArray[i+1], theArray[i]
flag = true
}
}
for j := theLen-1; j>0; j-- {
if(theArray[j-1] > theArray[j]) {
theArray[j], theArray[j-1] = theArray[j-1], theArray[j]
flag = true
}
}
if(!flag) {
break
}
}
return theArray
}
func main() {
var theArray = []int{10, 1, 18, 30, 23, 12, 7, 5, 18, 17}
fmt.Print("排序前")
fmt.Println(theArray)
fmt.Print("排序后")
arrayResult := cocktailSort(theArray)
fmt.Println(arrayResult)
}
运行结果如下
排序前[10 1 18 30 23 12 7 5 18 17]
排序后[1 5 7 10 12 17 18 18 23 30]
符合预期