Created
November 14, 2013 03:14
-
-
Save flengyel/7460737 to your computer and use it in GitHub Desktop.
Heap sort, lifted from Active State
This file contains 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 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