#!/usr/bin/python
import heapq
#第一种方法是根据堆排序的原理实现的。
def fixdown(a,k,n):#自顶向下堆化
N =n-1;
while 2*k<=N:
j=2*k;
if j<N and a[j]<a[j+1]:
j+= 1;
if a[k]<a[j]:
a[k],a[j]=a[j],a[k];
k=j;
else:
break;
def heapSort1(l):
n = len(l)-1;
for i in range(n//2,0,-1):
fixdown(l,i,len(l));
while n>1:
l[1],l[n]=l[n],l[1];
fixdown(l,1,n);
n-=1;
return l[1:];
#第二种方法是python自带的堆排序算法,基于小根堆。
def heapSort2(l):
l = l[1:];
heapq.heapify(l);
heap= [];
while l:
heap.append(heapq.heappop(l));
l[:]= heap;
return l;
l=[-1,26,5,77,1,61,11,59,15,48,19];#第一个元素不用,占位
res1 = heapSort1(l);
res2 = heapSort2(l);
print "first result of heapsorting:",(res1);
print "second result of heapsorting:",(res2);
运行结果: