1. 程式人生 > >go實現歸併排序演算法

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]

符合預期