(建议先看后边的伪代码分析,然后自己写出来)
先上代码:
import numpy as np length = 100000 array = np.arange(0, length) np.random.shuffle(array) def merge(array, s1, e1, s2, e2): array_new = array.copy() # 规定从小到大 steps = (e1-s1+1) + (e2-s2+1) start = s1 for i in range(steps): if s1 > e1: array_new[start+i] = array[s2] s2 += 1 continue if s2 > e2: array_new[start+i] = array[s1] s1 += 1 continue if array[s1] >= array[s2]: array_new[start+i] = array[s2] s2 += 1 elif array[s1] < array[s2]: array_new[start+i] = array[s1] s1 += 1 array[start:e2+1] = array_new[start:e2+1] return array_new def mergeSort(array, start, end): # 规定从小到大 if end-start == 1: if array[start] > array[end]: array[start] += array[end] array[end] = array[start] - array[end] array[start] = array[start] - array[end] return array if end == start: return array mid = int((start + end) / 2) mergeSort(array, start, mid) mergeSort(array, mid+1, end) merge(array, start, mid, mid+1, end) print(array) mergeSort(array, 0, length-1) print(array)
俺是非科班出生的菜鸡,一大把年纪了,第一次写归并排序