Skip to content

Instantly share code, notes, and snippets.

@flengyel
Created November 14, 2013 03:14
Show Gist options
  • Save flengyel/7460737 to your computer and use it in GitHub Desktop.
Save flengyel/7460737 to your computer and use it in GitHub Desktop.
Heap sort, lifted from Active State
def HeapSort(A):
def heapify(A):
start = (len(A) - 2) / 2
while start >= 0:
siftDown(A, start, len(A) - 1)
start -= 1
def siftDown(A, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and A[child] < A[child + 1]:
child += 1
if child <= end and A[root] < A[child]:
A[root], A[child] = A[child], A[root]
root = child
else:
return
heapify(A)
end = len(A) - 1
while end > 0:
A[end], A[0] = A[0], A[end]
siftDown(A, 0, end - 1)
end -= 1
if __name__ == '__main__':
from random import shiffle
a = range(12)
shuffle(a)
print a
HeapSort(a)
print a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment