python实现归并排序
import random from timewrap import cal_time # 一个计算时间的装饰器 def merge(li, low, mid, high): i = low j = mid + 1 li_tmp = [] while i <= mid and j <= high: if li[i] <= li[j]: li_tmp.append(li[i]) i += 1 else: li_tmp.append(li[j]) j += 1 while i <= mid: li_tmp.append(li[i]) i += 1 while j <= high: li_tmp.append(li[j]) j += 1 # li[low:high+1] = li_tmp for k in range(low, high+1): li[k] = li_tmp[k-low] def _merge_sort(li, low, high): if low < high: mid = (low + high) // 2 _merge_sort(li, low, mid) _merge_sort(li, mid+1, high) merge(li, low, mid, high) # print(li[low:mid + 1], li[mid + 1:high + 1]) @cal_time def merge_sort(li): _merge_sort(li, 0, len(li)-1) # li = [10,4,6,3,8,2,5,7] # merge_sort(li, 0, len(li)-1) # print(li) li = list(range(100000)) random.shuffle(li) merge_sort(li)