Bootstrap

【代码实现】归并排序代码实现(python)

归并排序代码实现


实现一组无序列表用归并排序的思维排序

#usr/bin/python
#coding=utf-8

'''
通过对递归的调用,实现(归并排序)(印象笔记有关于归并的详解,关键字-归并排序)
'''
def get(merge_sort): #递归 把列表一分为二
	if len(merge_sort)==1:
		return merge_sort
	if merge_sort == None:
		return [0]
	merge_left = merge_sort[0:len(merge_sort)/2]
	merge_right = merge_sort[len(merge_sort)/2:]

	merge_left = get(merge_left)
	merge_right = get(merge_right)

	merge_list = merge(merge_left,merge_right) #把两个列表合并
	print merge_list
	return merge_list  #一定要有return 把内层函数的结果传给外层函数,debug可以看到具体过程

def merge(a,b):
	ai = 0
	bi = 0
	if a == None: a=[0]
	if b == None: b=[0]
	merge_list = []
	while ai<len(a) and bi<len(b):
		if a[ai]<b[bi]:
			merge_list.append(a[ai])
			ai+=1
		else:
			merge_list.append(b[bi])
			bi += 1
	if ai<len(a):
		for aj in a[ai:]:
			merge_list.append(aj)
	elif bi<len(b):
		for bj in b[bi:]:
			merge_list.append(bj)
	return merge_list

merge_sort = [3,6,7,2,98,24,3684,35,34]
get(merge_sort)
;