def merge_sort(list0, le = lambda x,y:x<=y):
if len(list0)<=1:
return list0
num = len(list0) // 2
list1 = merge_sort(list0[:num],le)
list2 = merge_sort(list0[num:],le)
return merge(list1,list2,le)
def merge(list1, list2, le = lambda x,y:x<=y):
list1 = list1[:]
list2 = list2[:]
list3 = []
index1 = 0
index2 = 0
while index1 < len(list1) and index2 < len(list2):
if le(list1[index1], list2[index2]):
list3.append(list1[index1])
index1 += 1
else:
list3.append(list2[index2])
index2 += 1
list3 += list1[index1:]
list3 += list2[index2:]
return list3
def main():
list1 = [1,2,4,6,8]
list2 = [3,5,7,8,9]
print(merge(list1, list2))
list3 = [3, 1, 7, 5, 4, 2, 6]
print(merge_sort(list3))
if __name__ == '__main__':
main()
归并
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 归并排序:二路归并(稳定) 基本思想:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即...
- 核心思想就是,左边红色的数组,和右边绿色数组需要有序的合并成下面那个大数组。那插入方式也很简单,只要你先把左边儿的...