1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| def mergeSort(arr): if len(arr) // 2 == 0: return arr return merge(mergeSort(arr[0:len(arr) // 2]), mergeSort(arr[len(arr) // 2:]))
def merge(a_l, a_r): a = [0] * (len(a_l) + len(a_r)) p_l, p_r = 0, 0 while p_l < len(a_l) and p_r < len(a_r): if a_l[p_l] > a_r[p_r]: a[p_l + p_r] = a_r[p_r] p_r += 1 else: a[p_l + p_r] = a_l[p_l] p_l += 1 while p_l < len(a_l): a[p_l + p_r] = a_l[p_l] p_l += 1 while p_r < len(a_r): a[p_l + p_r] = a_r[p_r] p_r += 1 return a
if __name__ == '__main__': a = [16, 55, 64, 35, 24, 4, 85, 68, 84, 41] out = mergeSort(a) print(out) [out]: [4, 16, 24, 35, 41, 55, 64, 68, 84, 85]
|