归并排序

import random

def merge(li,low,mid,hight):
    i = low
    j = mid + 1
    tmp = []
    while i<=mid and j <= hight:
        if li[i] < li[j]:
            tmp.append(li[i])
            i += 1
        else:
            tmp.append(li[j])
            j += 1
    while i <= mid:
        tmp.append(li[i])
        i += 1
    while j <= hight:
        tmp.append(li[j])
        j += 1
    li[low:hight+1] = tmp

def merge_sort(li,low,hight):
    if low < hight:
        mid = (low + hight) // 2
        merge_sort(li,low,mid)
        merge_sort(li,mid+1,hight)
        merge(li,low,mid,hight)

def main():
    li = list(range(100))
    random.shuffle(li)
    print(li)
    merge_sort(li,0,len(li)-1)
    print(li)

if __name__ == '__main__':
    main()

  

posted @ 2021-11-28 15:09  NAVYSUMMER  阅读(50)  评论(0编辑  收藏  举报
交流群 编程书籍