To understand Heap Sort, you need go through the 'Heap' tutorial.
As we will be using the terms like,
So, to implement Heap Sort, we will be following the below steps :
Let us clarify using the below example :
We are given a list of 6 numbers,
So, the first step is to create a Heap.
Let's, follow the below steps to create a Heap :
Now, since we have build the Heap. Let us represent it in the form of an array to understand better.
Creating the above array is quite simple.
We take the root element 2 and place it in the 1st location of the array.
Similarly, take the elements 4 and 11 from Level 2 and place it in the 2nd and 3rd location of the array. And so on.
Now, it's time to apply the 'Delete Min' feature. i.e. Keep on removing the minimum element and placing them at the end of the Heap.
Now, as we know that the minimum element is the root element of the Heap.
So, take the minimum element i.e. 2 and swap it with the last element of the Heap i.e. 32.
Now, the Heap doesn't satisfy the structural property. i.e. 32 is greater than its children 4 and 11.
And since the children of 32 i.e. 4 and 11 are already Heaps. We can apply Heapify on 32.
After applying Heapify on 32,
So, we got a Heap again.
Now, let's apply 'Delete-Min' on it.
Since, the root element is the minimum element. Let's swap it with the last element i.e. 45(As 2 is not a part of Heap anymore).
Again, the above structure is not a Heap.
Let's apply Heapify on the root node 45.
Since, both the children of 45 i.e. 32 and 11 are Heaps. We can use Heapify on 45.
We got a Heap now. So, let's apply 'Min-Heap'.
Let's apply Heapify on 78 to make it a Heap.
If we continue the same process until there is no element left. We get the below Heap.
And if we look at the final Heap, we got the Heap in descending order.
There is a three step process involved in Heap Sort :
There is a three step process involved in Heap Sort :
Building a Heap can be done in O(n) time.
Removing the element takes O(log n) time.
Heapify takes O(log n) time.
Combining all the above running time, we get :
Total running time for Heap Sort : O(n log n)