Heap Sort Algorithms
Heap Sort Algorithms
Heap Sort Algorithms
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as
an optimization over selection sort where we first find the max (or min) element and swap it with the last (or
first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we
can quickly find and move the max element (In O(Log n) instead of O(n)) and hence achieve the O(n Log n)
time complexity.
Perform heap sort: Remove the maximum element in each step (i.e., move it to the end position and
remove that) and then consider the remaining elements and transform it into a max heap.
Delete the root element (10) from the max heap. In order to delete this node, try to swap it with the last
node, i.e. (1). After removing the root element, again heapify it to convert it into max heap.
o Resulted heap and array should look like this:
1
Repeat the above steps and it will look like the following:
Now when the root is removed once again it is sorted. and the sorted array will be like arr[] = {1, 3, 4,
5, 10} .
2
Complexity Analysis of Heap Sort
Time Complexity: O(n log n)
Auxiliary Space: O(log n), due to the recursive call stack. However, auxiliary space can be O(1) for
iterative implementation.
def heapSort(arr):
N = len(arr)
# Build a maxheap.
for i in range(N//2 - 1, -1, -1):
heapify(arr, N, i)
# Driver's code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
# Function call
heapSort(arr)
N = len(arr)
Output
Sorted array is
5 6 7 11 12 13
4
Disadvantages of Heap Sort
Costly : Heap sort is costly as the constants are higher compared to merge sort even if the time
complexity is O(n Log n) for both.
Unstable : Heap sort is unstable. It might rearrange the relative order.
Inefficient: Heap Sort is not very efficient because of the high constants in the time complexity.