python实现归并排序
Posted 小学弟-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)
以上是关于python实现归并排序的主要内容,如果未能解决你的问题,请参考以下文章