As you may know, heapsort is also one of the most asked sorting algorithms besides mergesort and quicksort and today we’re going to talk about it and I’ll try my best to explain it in much simpler terms as for a beginner it can be quite complicated more so if one has less knowledge about heaps. But fear not I’ve got your back. So now let’s get into it.
Before moving on to heap sort you need to know about the following terminologies to properly understand the working of heapsort.
So let’s begin by explaining the terms stated above
Heap data structure is a**_ complete binary tree that follows the heapify property_**. So what’s a complete binary tee you might ask?. A complete binary tree follows these conditions.
The heap is shown below following the heap property and this is called Max heap. It has the same root and the child nodes but there is a slight difference. The Complete Binay Tree doesn’t care whether it’s root node is smaller or larger but it is of grave importance in case of the heap data structure.
While creating a heap it is essential to follow the heap property which states as follows:
Heapify is the** process of creating a heap data structure from a binary tree. **Now Heapify is the most important operation on a heap data structure as it helps to maintain the structure of the heap after several operations have been performed on the heap like(insertion, deletion). We will be using this operation a lot and it will come in handy while designing heap sort.
working of heapify is shown below
2. Convert this array into a complete binary tree.
Complete binary tree created from the array
3. Create a heap from the binary tree.
After Heapify a max heap is created
Now that we’ve learned about all the important terms let’s start to create heap sort algorithm.
In a heap sort program, we’ll be given an unsorted array and we have to sort it. But heapsort works somewhat different than other sorting algorithms. By different, means the arrangement of each element after operations are performed. In this, the larger elements are sorted first in the last place then followed by the smaller elements, and at last, when there’s one element left that element would be the smallest and the last to go in it’s sorted place.
#sorting #sorting-algorithms #heap #heapsort #sort