递归排序法(MergeSorting)python

def mergesort(num=[]) :	
	#递归结束条件
	if len(num) < 2 :
		return num
	#分解列表,递归调用
	mid = len(num)//2
	left = mergesort(num[:mid])
	right = mergesort(num[mid:])
	#合并
	merged_list = []
	while left and right :
		if left[0] <= right[0] :
			merged_list.append(left.pop(0))
		else :
			merged_list.append(right.pop(0))		
	merged_list.extend(right if right else left)		
	return merged_list
	
	
num = [1, 5, 4, 2, 23, 15, 2, 45, 56, 7, 8, 9]
print(mergesort(num))

'''
[1, 2, 2, 4, 5, 7, 8, 9, 15, 23, 45, 56]
'''

你可能感兴趣的:(python杂记,算法)