Skip to content

Instantly share code, notes, and snippets.

@elliott-beach
Forked from showell/heap.py
Last active February 8, 2017 16:06
Show Gist options
  • Save elliott-beach/60bbe77cf256b12b82b6a27e63c5de07 to your computer and use it in GitHub Desktop.
Save elliott-beach/60bbe77cf256b12b82b6a27e63c5de07 to your computer and use it in GitHub Desktop.
heapsort in Python
def swap(a, i, j):
a[i], a[j] = a[j], a[i]
def heapify(a, n, max):
while True:
biggest = n
c1 = 2*n + 1
c2 = c1 + 1
for c in [c1, c2]:
if c < max and a[c] > a[biggest]:
biggest = c
if biggest == n:
return
swap(a, n, biggest)
n = biggest
def build_max_heap(a):
i = len(a) / 2 - 1
max = len(a)
while i >= 0:
heapify(a, i, max)
i -= 1
def heapsort(a):
build_max_heap(a)
j = len(a) - 1
while j > 0:
swap(a, 0, j)
heapify(a, 0, j)
j -= 1
a = range(10)
heapsort(a)
print a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment