import random
def mergeSort(seq, reverse=False):
#把原列表分成两部分
mid = len(seq) // 2
left, right = seq[:mid], seq[mid:]
#根据需要进行递归
if len(left) > 1:
left = mergeSort(left)
if len(right) > 1:
right = mergeSort(right)
#现在前后两部分都已排序
#进行合并
temp = []
while left and right:
if left[-1] >= right[-1]:
temp.append(left.pop())
else:
temp.append(right.pop())
temp.reverse()
result = (left or right) + temp
#根据需要进行逆序
if reverse:
result.reverse()
return result
#测试
for i in range(100000):
#生成随机测试数据
reverse = random.choice((True, False))
x = [random.randint(1,100) for i in range(20)]
y = sorted(x, reverse=reverse)
x = mergeSort(x, reverse)
if x!=y:
print('error')
附:Python程序的__name__属性作用与用法演示视频