排序算法学习(python版本)之堆排序(HeapSort)

8 篇文章 0 订阅
6 篇文章 0 订阅
[b]Contains:[/b]
堆排序以及堆排序的应用
[b]堆排序(Heapsort)[/b]是指利用堆積這種資料結構所設計的一種排序算法。堆積是一個近似完滿二元樹的結構,並同時滿足堆積的性質:即子結點的键值或索引總是小於(或者大於)它的父節點。
[list]
[*]最差时间复杂度:O(nlogn)
[*]最优时间复杂度:O(nlogn)
[*]平均时间复杂度:O(nlogn)
[/list]
[b]建立堆,保持最大堆,堆排序(顶端最大元素与最后一个元素不断的交换)——整个过程。[/b]
[code="python"]#-*-coding:utf-8-*-

def heap_sort(lst):
for start in range((len(lst)-2)/2, -1, -1):
siftdown(lst,start,len(lst)-1)
for end in range(len(lst)-1, 0, -1):
lst[end], lst[0] = lst[0], lst[end]
siftdown(lst, 0, end - 1)
return lst

def siftdown(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[child] > lst:
lst[child],lst = lst,lst[child]
root=child
else:
break

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

if __name__ == '__main__':
main()[/code]
[b]使用heapq[/b]

#!/usr/bin/env python
#-*-encoding:utf-8-*-
from heapq import heappush,heappop

def heap_sort(iterable):
h = []
for value in iterable:
heappush(h, value)
return [heappop(h) for i in range(len(h))]

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

if __name__ == "__main__":
main()


参考资料:
http://zh.wikipedia.org/wiki/%E5%A0%86%E6%8E%92%E5%BA%8F
http://blog.csdn.net/v_july_v/article/details/6198644
http://docs.python.org/2/library/heapq.html
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
http://en.wikipedia.org/wiki/Heapsort
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值