1 def merge_(li, start, mid, end): 2 i = start 3 j = mid + 1 4 ltmp = [] 5 while j <= end and i <= mid: 6 if li[i] < li[j]: 7 ltmp.append(li[i]) 8 i += 1 9 else: 10 ltmp.append(li[j]) 11 j += 1 12 while i <= mid: 13 ltmp.append(li[i]) 14 i += 1 15 while j <= end: 16 ltmp.append(li[j]) 17 j += 1 18 li[start:end+1] = ltmp 19 20 def mergesort(li, start, end): 21 if start < end: 22 mid = (start+end) // 2 23 mergesort(li, start, mid) 24 mergesort(li, mid+1, end) 25 merge_(li, start, mid, end) 26 print(li[start:end+1]) 27 28 li = list(range(8)) 29 import random 30 random.shuffle(li) 31 print(li) 32 mergesort(li, 0, len(li)-1) 33 print(li)