【归并排序思想】
分治的思想(递归)
# coding = utf-8
import random
import sys
#归并排序
list = []
# 随机生成列表
def generate():
n = int(input("请输入本次排序数字个数:"))
while n > 0:
list.append(random.randint(0,1000))
n -= 1
print("生成的数字列表如下:%s" %list)
def marge(leftList,rightList):
otherList = []
h = j = 0
while j < len(leftList) and h < len(rightList):
if leftList[j] < rightList[h]:
otherList.append(leftList[j])
j += 1
else:
otherList.append(rightList[h])
h += 1
if j == len(leftList):
for i in rightList[h:]:
otherList.append(i)
else:
for i in leftList[j:]:
otherList.append(i)
return otherList
# 对列表进行归并排序
def margeSort(markList):
if len(markList) <= 1:
return markList
middle = len(markList) // 2
leftList = margeSort(markList[:middle])
rightList = margeSort(markList[middle:])
return marge(leftList,rightList)
def main():
generate()
print("排序后数字列表如下:%s" % margeSort(list))
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
sys.stderr.write("退出\n")
sys.exit(0)