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.

  1. Heaps
  2. Heap Property
  3. Heapify

So let’s begin by explaining the terms stated above

1. Heaps

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.

  • All nodes in every level of the tree are filled except the leaf nodes.
  • The nodes are as far left as possible.

Complete Binary Tree

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.

Heap

2. Heap Property

While creating a heap it is essential to follow the heap property which states as follows:

  • The heap where the parent node is always greater than the child nodes and provided that the root node is largest is called a Max-heap.

Max Heap

  • The heap in which the child node is always greater than it’s child nodes and the root node is the smallest node is called a Min-heap.

Min heap

3. Heapify

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

  1. Select an input array.

Input array

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

Heap Sort Explained
2.10 GEEK