Created
March 5, 2013 07:50
-
-
Save jo32/5088666 to your computer and use it in GitHub Desktop.
heap sort test code
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
# implemented according to the psudocode from: | |
# http://en.wikipedia.org/wiki/Heapsort (2013/03/05) | |
def heapSort(unsortedList): | |
heapify(unsortedList) | |
end = len(unsortedList) - 1 | |
while end > 0: | |
unsortedList[end], unsortedList[0] = unsortedList[0], unsortedList[end] | |
end -= 1 | |
shiftDown(unsortedList, 0, end) | |
def heapify(unsortedList): | |
start = (len(unsortedList) - 2) / 2 | |
while (start >= 0): | |
shiftDown(unsortedList, start, len(unsortedList) - 1) | |
start -= 1 | |
def shiftDown(unsortedList, start, end): | |
root = start | |
while root * 2 + 1 <= end: | |
child = root * 2 + 1 | |
swap = root | |
if unsortedList[root] < unsortedList[child]: | |
swap = child | |
child += 1 | |
if child <= end and unsortedList[swap] < unsortedList[child]: | |
swap = child | |
if swap != root: | |
unsortedList[swap], unsortedList[root] = unsortedList[root], unsortedList[swap] | |
root = swap | |
else: | |
return | |
if __name__ == '__main__': | |
a = [0, 1, 999, 1, 1] | |
heapSort(a) | |
print a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment