golang 归并排序

package sort
//归并排序
func MergeSort(arr []int)  {
	arrcount := len(arr)
	if arrcount > 1 {
		MergeSort(arr[:arrcount/2])
		MergeSort(arr[arrcount/2:])
		res:= Merge(arr[:arrcount/2],arr[arrcount/2:])
		copy(arr,res)
	}
}
func Merge(arr1,arr2 []int )[]int  {
	res := make([]int,len(arr1)+len(arr2))
	i,j,k,arr1count,arr2count := 0,0,0,len(arr1),len(arr2)		//声明并初始化arr1,arr2的游针,cout
	//如果这两个游针在这两个cout的范围内
	for i < arr1count && j < arr2count{
		if arr1[i] < arr2[j]{
			res[k] = arr1[i]
			k++;i++

		}else {
				res[k] = arr2[j]
				k++;j++
		}//else end
	}//if end
	//对比完成,已经有一方超出数组长度,此时将别一方多余的也合并出res切片
	for i<arr1count{
		res[k]=arr1[i]
		k++;i++
		}
	for j<arr2count{
		res[k]= arr2[j]
		k++;j++
	}
	return res
}

你可能感兴趣的:(Golang)