您的位置:首页 > 编程语言 > Python开发

Python实现的几种排序(来自wiki百科)

2014-04-14 13:53 148 查看
1.归并排序:

def merge(l1,l2):
final=[]
#对l1,l2进行排序
l1 = merge(l1)
l2 = merge(l2)
while l1 and l2:
if l1[0]<=l2[0]:
final.append(l1.pop(0))
else:
final.append(l2.pop(0))
return final+l1+l2


2.堆排序
#!/usr/bin/env python
#-*-coding:utf-8-*-

def heap_sort(lst):
for start in range((len(lst)-2)/2,-1,-1):
sift_down(lst,start,len(lst)-1)

for end in range(len(lst)-1,0,-1):
lst[0],lst[end] = lst[end],lst[0]
sift_down(lst,0,end-1)
return lst

def sift_down(lst,start,end):
root = start
while True:
child = 2*root + 1
if child > end:break
if child+1 <= end and lst[child] < lst[child+1]:
child += 1
if lst[root] < lst[child]:
lst[root],lst[child] = lst[child],lst[root]
root = child
else:
break

def main():
l = [9,2,1,7,6,8,5,3,4]
heap_sort(l)

if __name__ == "__main__":
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: