合并两个有序列表

1.尾递归

 1 def _recursion_merge_sort2(l1, l2, tmp):
 2     if len(l1) == 0 or len(l2) == 0:
 3         tmp.extend(l1)
 4         tmp.extend(l2)
 5         return tmp
 6     else:
 7         if l1[0] < l2[0]:
 8             tmp.append(l1[0])
 9             del l1[0]
10         else:
11             tmp.append(l2[0])
12             del l2[0]
13         return _recursion_merge_sort2(l1, l2, tmp)
14 
15 def recursion_merge_sort2(l1, l2):
16     return _recursion_merge_sort2(l1, l2, [])

2.循环算法

思路:

  • 定义一个新的空列表
  • 比较两个列表的首个元素
  • 小的就插入到新列表里
  • 把已经插入新列表的元素从旧列表删除
  • 直到两个旧列表有一个为空
  • 再把旧列表加到新列表后面
     1 def loop_merge_sort(l1, l2):
     2     tmp = []
     3     while len(l1) > 0 and len(l2) > 0:
     4         if l1[0] < l2[0]:
     5             tmp.append(l1[0])
     6             del l1[0]
     7         else:
     8             tmp.append(l2[0])
     9             del l2[0]
    10     tmp.extend(l1)
    11     tmp.extend(l2)
    12     return tmp

     

循环算法

posted @ 2020-04-23 09:43  燕十三丶  阅读(215)  评论(0编辑  收藏  举报
AmazingCounters.com