go实现归并排序算法
前面我们讲了归并排序算法,接下来我们来讲讲go的代码实现呗,如下
package main
import "fmt"
//合并排序
func lastMergeSort(list1 []int, list2 []int) []int{
i, j := 0,0
//temp := make([]int,0)
var temp[]int
for i < len(list1) && j < len(list2) {
if (list1[i] <= list2[j]) {
temp = append(temp, list1[i])
i++
}else {
temp = append(temp, list2[j])
j++
}
}
if (i == len(list1)) {
for ; j <len(list2); j++ {
temp = append(temp, list2[j])
}
}
if (j == len(list2)) {
for ; i <len(list1); i++ {
temp = append(temp, list1[i])
}
}
return temp;
}
func mergeSort(theArray []int )[]int {
if(len(theArray)==1) {
return theArray
}
mid := len(theArray)/2
leftArray := mergeSort(theArray[:mid])
rightArray := mergeSort(theArray[mid:])
return lastMergeSort(leftArray, rightArray);
}
func main() {
var theArray = []int{6, 4, 5, 1, 8, 7, 2, 3}
fmt.Print("排序前")
fmt.Println(theArray)
fmt.Print("排序后")
arrayResult := mergeSort(theArray)
fmt.Println(arrayResult)
}
执行结果如下
排序前[6 4 5 1 8 7 2 3]
排序后[1 2 3 4 5 6 7 8]
符合预期
还没有评论,来说两句吧...