Explore
ProGrad Programs
Placement Prep
TCS Codevita
Live Placement Training
Live Aptitude Training
Live Programming Training
Webinars
About Us

Edit
Reply




Edit

Heap Sort Program in C, C++, Java with Examples | FACE Prep

Published on 12 Mar 2020

In this article, we will be discussing Heap Sort program in C, C++ and Java with examples. Heap sort algorithm implementation, Heap sort pseudocode, time complexity, etc are also discussed in this article.


Prerequisites: Merge Sort, Insertion Sort


´╗┐What is Heap Sort Algorithm?


Before we get into Heap sort, let's understand what a Heap data structure is.


Heap is a special kind of binary tree in which elements are stored in a hierarchical manner. Heap has some additional rules it must always have a heap structure, where all the levels of the binary tree are filled up from left to right. Second, it must either be ordered as a max heap or a min-heap.


  • Max heap Parent node is greater than or equal to the value of its children node
  • Min heap Parent node is less than or equal to the value of its children node


In Heap sort, we will be dealing with Max heap. Using max heaps, we can sort an unsorted array of elements. In simple, this is how it works


heap sort in c

Heap Sort Example


Lets see how sorting takes place with the help of heap.Consider an array arr[] = {4, 3, 7, 1, 8, 5}


1) Firstly, lets convert the given array to a binary tree.The representation of a binary tree for the given array looks as shown below.


heap sort program in c


2) Next, build max-heap from the above tree. A max tree is where all the parent nodes are of higher value than the children nodes.


heap sort program in c


3) Now, swap the root node with the last element of the heap node. This means largest value has moved to its correct position. So, remove the largest value from the tree. After removing, the tree looks as shown below.


heat sort program in c


4) Repeat step 3 until no elements are left in the heap



heap sort program in c


heap sort program in c


heap sort program in c


heap sort program in c


heap sort algorithm in c


Heap Sort Program in C, C++, Java


Here is the implementation of Heap sort in various languages.\


C
C++
Java

Output
Input- 4 3 7 1 8 5 Output- 1 3 4 57 8


Heap Sort Time Complexity


To calculate the time complexity of heap sort, let us first try to break down & understand the time-complexities of individual functions.


  • To build max heap the actual complexity is O(n).
  • The complexity to swap the largest element with the last element of the array is O(log n).


Since Heap sort runs in linearithmic time, the combination of these two-time complexities is O(n logn) and hence the time complexity of Heap sort is O(n logn).


Check out more Data Structure Questions


Also See Similar DS Sorting Techniques


If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in