Friday, November 13, 2015

Heapsort in Python

def parent(i):
return i/2

def  left(i):
return 2*i

def  right(i):
return 2*i+1


def heapify(A,i,n):
l=left(i)
r=right(i)
largest=i
if l<=n and A[l]>A[largest]:
largest=l
if r<=n and A[r]>A[largest]:
largest=r
if largest!=i:
A[i],A[largest] =A[largest],A[i]
heapify(A,largest,n)


def length(A):return len(A)-1

def buildheap(A):
n=length(A)
for x in xrange(n/2,-1,-1):
print x
heapify(A,x,length(A))

def heapsort(A):
buildheap(A)
heapsize=length(A)
for i in xrange(heapsize,0,-1) :

A[0],A[i]=A[i],A[0]
heapsize=heapsize-1
heapify(A,0,heapsize)

A=[4,8,1,2,11,3,9]
heapsort(A)
print A

No comments:

Post a Comment

Contributors

Translate