defmerge(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 if li[i] >= li[j]: 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 for i in range(low, high+1): li[i] = li_tmp[i-low]
例题:已知两个有序列表,实现将这两个列表合并排序
代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
defmerge_sort(li1, li2): i = 0 j = 0 li = [] while i < len(li1) and j < len(li2): if li[i] >= li[j]: li.append(li[j]) j += 1 else: li.append(li[i]) i += 1 while i < len(li1): li.append(li[i]) i += 1 while j < len(li2): li.append(li[j]) j += 1