前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python版归并排序算法(附Python程序__name__属性用法演示视频)

Python版归并排序算法(附Python程序__name__属性用法演示视频)

作者头像
Python小屋屋主
发布2018-04-16 15:05:52
7770
发布2018-04-16 15:05:52
举报
文章被收录于专栏:Python小屋

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__属性作用与用法演示视频

视频内容
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2016-11-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档