In the previous article, we introduced the heapsort algorithm and coded several helper functions in Python. In this article, we will finally code the heapsort function and test it on some input data.
To recap, we already introduced the following functions:
- heapify: Turns a list into a binary heap.
- rebuildHeap: Accepts as input a heap with the root node deleted and rebuilds the heap.
- consolidateHeap: Moves all empty nodes to the bottom of the heap so we can shrink the heap.
- swap: Swaps the contents of two variables.
Since we did all the heavy lifting in writing the helper functions, coding heapSort is rather simple:
def heapSort(L):
'''Given a list, perform a binary sort on it
'''
# First, reconstitute list as a binary heap:
heapify(L)
high = len(L)
# While there is still data in the heap,
# remove the root node, rebuild and
# consolidate the heap, and move the old
# root node to the end
while high > 0:
# Delete root node; save in temp
temp = L[0]
L[0] = None
# Rebuild and consolidate heap
rebuildHeap(L,0,high)
consolidateHeap(L,high)
high -= 1
# Move old root node to end
L[high] = temp
As you can see, once we create the heap, all we are doing is [1] deleting the root node from the heap by setting its value to “None”; [2] rebuild the heap and consolidate the heap; [3] decrement the variable indicating the size of the heap; [4] move the old root node back into the list right after the heap; [5] repeat until the heap size is 0. You may have noticed that when we call rebuildHeap and consolidateHeap, we specify the size of the heap. This is to ensure the sorted list which we are inserting at the end of the list is not treated as part of the heap.
To test our heapsort function, I reused the list from the previous article, and used the following code:
>>> myList = [123,79,29,997,519,17,239,144,51,372]
>>> heapSort(myList)
>>> print(myList)
[17, 29, 51, 79, 123, 144, 239, 372, 519, 997]
As you can see, the heapsort function seems to work, and has the added advantage (over merge sort) of supporting the ability to sort in place. In the next article, we’ll examine one more efficient sorting algorithm: quicksort.
The source code for this heapsort implementation can be found here.
Recent Comments