经典归并排序算法 -- Python

时间:2022-12-22 23:24:41
# -*- coding: UTF-8 -*- def merge(a,b): c = [] i = 0 j = 0 while i < len(a) and j < len(b): if a[i] < b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 c.extend(a[i:]) c.extend(b[j:]) return c def mergesort(arr): if len(arr) <= 1: return arr else: m = len(arr) / 2 c1 = mergesort(arr[:m]) c2 = mergesort(arr[m:]) return merge(c1,c2) if __name__ == "__main__": arr = [3,4,1,2,2,5,4,3,6,2] result = mergesort(arr) # 切记,mergesort 没改变原来的数组 print(result)