-
-
Save elliott-beach/60bbe77cf256b12b82b6a27e63c5de07 to your computer and use it in GitHub Desktop.
heapsort in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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