1、算法介绍
归并排序采用分而治之的思想进行排序,需要额外的内存空间。
(1)申请arrRes与未排序序列arr相同内存空间,用于存放归并后的序列
(2)将未排序序列分为两份arrL与arrR,从arrL与arrR分别取出一个元素进行比较,较小的并入arrRes序列,
从并入元素所属的序列取下一个进行比较,直至序列arrL与arrR一方全部并入arrRes,将剩余的一方直接并入arrRes
(3)递归步骤(2),递归结束,归并完成
2、代码实现
2.1、golang
package main import ( "fmt" ) func main() { slice := []int{5, 3, 12, 54, 23, 12, 6, 9, 19} slice = SortMerge(slice) fmt.Println(slice) } //归并排序 func SortMerge(slice []int) []int { n := len(slice) if n < 2 { return slice } middle := n / 2 left := slice[:middle] right := slice[middle:] return merge(SortMerge(left), SortMerge(right)) } //归并元素 func merge(left, right []int) []int { var result []int for len(left) != 0 && len(right) != 0 { if left[0] <= right[0] { result = append(result, left[0]) left = left[1:] } else { result = append(result, right[0]) right = right[1:] } } result = append(result, left...) result = append(result, right...) return result }
2.2、python3
# 归并排序 def sort_merge(arr): n = len(arr) if n < 2: return arr middle = n // 2 left, right = arr[0:middle], arr[middle:] return __merge(sort_merge(left), sort_merge(right)) # 左右归并 def __merge(left, right): result = [] while left and right: if left[0] <= right[0]: result.append(left.pop(0)) else: result.append(right.pop(0)) return result + left + right if __name__ == '__main__': arr = [5, 3, 12, 54, 23, 12, 6, 9, 19] arr = sort_merge(arr) print(arr)