Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Heap
  • Practice Heap
  • MCQs on Heap
  • Heap Tutorial
  • Binary Heap
  • Building Heap
  • Binomial Heap
  • Fibonacci Heap
  • Heap Sort
  • Heap vs Tree
  • Leftist Heap
  • K-ary Heap
  • Advantages & Disadvantages
Open In App
Next Article:
Find k largest elements in an array
Next article icon

Iterative HeapSort

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. 

Examples:

Input :  10 20 15 17 9 21  Output : 9 10 15 17 20 21     Input:  12 11 13 5 6 7 15 5 19  Output: 5 5 6 7 11 12 13 15 19 

In first Example, first we have to build Max Heap. 

So, we will start from 20 as child and check for its parent. Here 10 is smaller, so we will swap these two. 

Now, 20 10 15 17 9 21 

Now, child 17 is greater than its parent 10. So, both will be swapped and order will be 20 17 15 10 9 21 

Now, child 21 is greater than parent 15. So, both will be swapped. 

20 17 21 10 9 15 

Now, again 21 is bigger than parent 20. So, 21 17 20 10 9 15 

This is Max Heap. 

Now, we have to apply sorting. Here, we have to swap first element with last one and we have to maintain Max Heap property. So, after first swapping : 15 17 20 10 9 21 It clearly violates Max Heap property. 

So, we have to maintain it. So, order will be 

20 17 15 10 9 21 

17 10 15 9 20 21 

15 10 9 17 20 21 

10 9 15 17 20 21 

9 10 15 17 20 21 

Here, underlined part is sorted part.

Implementation:

C++
// C++ program for implementation  // of Iterative Heap Sort #include <bits/stdc++.h> using namespace std;  // function build Max Heap where value  // of each child is always smaller // than value of their parent void buildMaxHeap(int arr[], int n)  {      for (int i = 1; i < n; i++)      {         // if child is bigger than parent         if (arr[i] > arr[(i - 1) / 2])          {             int j = i;                  // swap child and parent until             // parent is smaller             while (arr[j] > arr[(j - 1) / 2])              {                 swap(arr[j], arr[(j - 1) / 2]);                 j = (j - 1) / 2;             }         }     } }  void heapSort(int arr[], int n)  {     buildMaxHeap(arr, n);      for (int i = n - 1; i > 0; i--)     {         // swap value of first indexed          // with last indexed          swap(arr[0], arr[i]);              // maintaining heap property         // after each swapping         int j = 0, index;                  do         {             index = (2 * j + 1);                          // if left child is smaller than              // right child point index variable              // to right child             if (arr[index] < arr[index + 1] &&                                 index < (i - 1))                 index++;                      // if parent is smaller than child              // then swapping parent with child              // having higher value             if (arr[j] < arr[index] && index < i)                 swap(arr[j], arr[index]);                      j = index;                  } while (index < i);     } }  // Driver Code to test above int main()  {     int arr[] = {10, 20, 15, 17, 9, 21};     int n = sizeof(arr) / sizeof(arr[0]);          printf("Given array: ");     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);              printf("\n\n");       heapSort(arr, n);      // print array after sorting     printf("Sorted array: ");     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);      return 0; } 
C
// C program for implementation // of Iterative Heap Sort #include <stdio.h>  // function build Max Heap where value // of each child is always smaller // than value of their parent void buildMaxHeap(int arr[], int n) {     for (int i = 1; i < n; i++)     {         // if child is bigger than parent         if (arr[i] > arr[(i - 1) / 2])         {             int j = i;                  // swap child and parent until             // parent is smaller             while (arr[j] > arr[(j - 1) / 2])             {                 int temp=arr[j];                 arr[j]=arr[(j-1)/2];                 arr[(j-1)/2]=temp;                 j = (j - 1) / 2;             }         }     } }  void heapSort(int arr[], int n) {     buildMaxHeap(arr, n);      for (int i = n - 1; i > 0; i--)     {         // swap value of first indexed         // with last indexed         int temp=arr[0];         arr[0]=arr[i];         arr[i]=temp;              // maintaining heap property         // after each swapping         int j = 0, index;                  do         {             index = (2 * j + 1);                          // if left child is smaller than             // right child point index variable             // to right child             if (arr[index] < arr[index + 1] &&                                 index < (i - 1))                 index++;                      // if parent is smaller than child             // then swapping parent with child             // having higher value             if (arr[j] < arr[index] && index < i)             {                 int tem1=arr[j];                 arr[j]=arr[index];                 arr[index]=tem1;             }                      j = index;                  } while (index < i);     } }  // Driver Code to test above int main() {     int arr[] = {10, 20, 15, 17, 9, 21};     int n = sizeof(arr) / sizeof(arr[0]);          printf("Given array: ");     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);              printf("\n\n");      heapSort(arr, n);      // print array after sorting     printf("Sorted array: ");     for (int i = 0; i < n; i++)         printf("%d ", arr[i]);      return 0; } 
Java
// Java implementation of Iterative Heap Sort  public class HeapSort {    // function build Max Heap where value   // of each child is always smaller   // than value of their parent   static void buildMaxHeap(int arr[], int n)   {     for (int i = 1; i < n; i++)     {       // if child is bigger than parent       if (arr[i] > arr[(i - 1) / 2])       {         int j = i;          // swap child and parent until         // parent is smaller         while (arr[j] > arr[(j - 1) / 2])         {           swap(arr, j, (j - 1) / 2);           j = (j - 1) / 2;         }       }     }   }    static void heapSort(int arr[], int n)   {     buildMaxHeap(arr, n);      for (int i = n - 1; i > 0; i--)     {       // swap value of first indexed       // with last indexed       swap(arr, 0, i);        // maintaining heap property       // after each swapping       int j = 0, index;        do       {         index = (2 * j + 1);          // if left child is smaller than         // right child point index variable         // to right child         if (index < (i - 1) && arr[index] < arr[index + 1])           index++;          // if parent is smaller than child         // then swapping parent with child         // having higher value         if (index < i && arr[j] < arr[index])           swap(arr, j, index);          j = index;        } while (index < i);     }   }    public static void swap(int[] a, int i, int j) {     int temp = a[i];     a[i]=a[j];     a[j] = temp;   }    /* A utility function to print array of size n */   static void printArray(int arr[])   {     int n = arr.length;     for (int i = 0; i < n; i++)       System.out.print(arr[i] + " ");     System.out.println();   }    // Driver program   public static void main(String args[])   {     int arr[] = {10, 20, 15, 17, 9, 21};     int n = arr.length;      System.out.print("Given array: ");     printArray(arr);      heapSort(arr, n);      System.out.print("Sorted array: ");     printArray(arr);   } } 
Python3
# Python3 program for implementation  # of Iterative Heap Sort   # function build Max Heap where value  # of each child is always smaller  # than value of their parent  def buildMaxHeap(arr, n):       for i in range(n):                  # if child is bigger than parent          if arr[i] > arr[int((i - 1) / 2)]:             j = i                   # swap child and parent until              # parent is smaller              while arr[j] > arr[int((j - 1) / 2)]:                 (arr[j],                   arr[int((j - 1) / 2)]) = (arr[int((j - 1) / 2)],                                             arr[j])                 j = int((j - 1) / 2)  def heapSort(arr, n):       buildMaxHeap(arr, n)       for i in range(n - 1, 0, -1):                  # swap value of first indexed          # with last indexed          arr[0], arr[i] = arr[i], arr[0]              # maintaining heap property          # after each swapping          j, index = 0, 0                  while True:             index = 2 * j + 1                          # if left child is smaller than              # right child point index variable              # to right child              if (index < (i - 1) and                  arr[index] < arr[index + 1]):                  index += 1                      # if parent is smaller than child              # then swapping parent with child              # having higher value              if index < i and arr[j] < arr[index]:                  arr[j], arr[index] = arr[index], arr[j]                       j = index              if index >= i:                 break  # Driver Code if __name__ == '__main__':     arr = [10, 20, 15, 17, 9, 21]      n = len(arr)           print("Given array: ")     for i in range(n):         print(arr[i], end = " ")               print()       heapSort(arr, n)       # print array after sorting      print("Sorted array: ")     for i in range(n):         print(arr[i], end = " ")  # This code is contributed by PranchalK 
C#
// C# implementation of Iterative Heap Sort  using System;      class HeapSort  {  // function build Max Heap where value // of each child is always smaller // than value of their parent static void buildMaxHeap(int []arr, int n) {     for (int i = 1; i < n; i++)     {         // if child is bigger than parent         if (arr[i] > arr[(i - 1) / 2])         {             int j = i;                  // swap child and parent until             // parent is smaller             while (arr[j] > arr[(j - 1) / 2])             {                 swap(arr, j, (j - 1) / 2);                 j = (j - 1) / 2;             }         }     } }  static void heapSort(int []arr, int n) {     buildMaxHeap(arr, n);      for (int i = n - 1; i > 0; i--)     {                  // swap value of first indexed         // with last indexed         swap(arr, 0, i);              // maintaining heap property         // after each swapping         int j = 0, index;              do         {             index = (2 * j + 1);                  // if left child is smaller than             // right child point index variable             // to right child             if (index < (i - 1) && arr[index] <                                     arr[index + 1])             index++;                  // if parent is smaller than child             // then swapping parent with child             // having higher value             if (index < i && arr[j] < arr[index])                 swap(arr, j, index);                  j = index;              } while (index < i);     } }  public static void swap(int[] a, int i, int j)  {     int temp = a[i];     a[i] = a[j];     a[j] = temp; }  /* A utility function to print array of size n */ static void printArray(int []arr) {     int n = arr.Length;     for (int i = 0; i < n; i++)     Console.Write(arr[i] + " ");     Console.WriteLine(); }  // Driver Code public static void Main(String []args) {     int []arr = {10, 20, 15, 17, 9, 21};     int n = arr.Length;      Console.Write("Given array: ");     printArray(arr);      heapSort(arr, n);      Console.Write("Sorted array: ");     printArray(arr); } }  // This code is contributed by Princi Singh 
JavaScript
<script> // javascript program for implementation  // of Iterative Heap Sort  function swap(arr, i, j) {     let temp = arr[i];     arr[i] = arr[j];     arr[j] = temp; }  // function build Max Heap where value  // of each child is always smaller // than value of their parent function buildMaxHeap(arr, n) {     for(let i=1;i<n;i++)     {         // if child is bigger than parent         if (arr[i] > arr[(i - 1) / 2])          {             let j = i;                  // swap child and parent until             // parent is smaller             while (arr[j] > arr[(j - 1) / 2])              {                 swap(arr,j,(j-1)/2);                 j = (j - 1) / 2;             }         }     } }    function heapSort(arr, n) {          buildMaxHeap(arr,n);          for (let i = n - 1; i > 0; i--)     {         // swap value of first indexed          // with last indexed          swap(arr,0,i);              // maintaining heap property         // after each swapping         let j = 0, index;                  do         {             index = (2 * j + 1);                          // if left child is smaller than              // right child point index variable              // to right child             if (arr[index] < arr[index + 1] && index < (i - 1))             index++;                      // if parent is smaller than child              // then swapping parent with child              // having higher value             if (arr[j] < arr[index] && index < i)                 swap(arr, j, index);                      j = index;                  } while (index < i);     } }   // Driver Code to test above let arr = [10, 20, 15, 17, 9, 21];  let n = arr.length;  document.write("Given array : "); for (let i = 0; i < n; ++i)         document.write(arr[i]+" ");          document.write("<br>");  heapSort(arr,n);  // print array after sorting document.write("Sorted array : "); for (let i = 0; i < n; ++i)         document.write(arr[i]+" ");   // This code is contributed by aditya942003patil   </script> 

Output
Given array: 10 20 15 17 9 21     Sorted array: 9 10 15 17 20 21 

Time Complexity: O(n log n), Here, both function buildMaxHeap and heapSort runs in O(nlogn) time.
Auxiliary Space: O(1)


Next Article
Find k largest elements in an array

K

kaditya139
Improve
Article Tags :
  • Algorithms
  • Sorting
  • Heap
  • DSA
Practice Tags :
  • Algorithms
  • Heap
  • Sorting

Similar Reads

    Heap Data Structure
    A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree.Basics
    2 min read
    Introduction to Heap - Data Structure and Algorithm Tutorials
    A Heap is a special tree-based data structure with the following properties:It is a complete binary tree (all levels are fully filled except possibly the last, which is filled from left to right).It satisfies either the max-heap property (every parent node is greater than or equal to its children) o
    15+ min read
    Binary Heap
    A Binary Heap is a complete binary tree that stores data efficiently, allowing quick access to the maximum or minimum element, depending on the type of heap. It can either be a Min Heap or a Max Heap. In a Min Heap, the key at the root must be the smallest among all the keys in the heap, and this pr
    13 min read
    Advantages and Disadvantages of Heap
    Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
    2 min read
    Time Complexity of building a heap
    Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is O(n * lg(n)) since each call to Heapify costs O(lg(n)) and Build-Heap makes O(n) such calls. This upper bound, though correct, is not asymptotically
    2 min read
    Applications of Heap Data Structure
    Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
    2 min read
    Comparison between Heap and Tree
    What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
    3 min read
    When building a Heap, is the structure of Heap unique?
    What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
    4 min read

    Some other type of Heap

    Binomial Heap
    The main application of Binary Heap is to implement a priority queue. Binomial Heap is an extension of Binary Heap that provides faster union or merge operation with other operations provided by Binary Heap. A Binomial Heap is a collection of Binomial Trees What is a Binomial Tree? A Binomial Tree o
    15 min read
    Fibonacci Heap | Set 1 (Introduction)
    INTRODUCTION:A Fibonacci heap is a data structure used for implementing priority queues. It is a type of heap data structure, but with several improvements over the traditional binary heap and binomial heap data structures.The key advantage of a Fibonacci heap over other heap data structures is its
    5 min read
    Leftist Tree / Leftist Heap
    INTRODUCTION:A leftist tree, also known as a leftist heap, is a type of binary heap data structure used for implementing priority queues. Like other heap data structures, it is a complete binary tree, meaning that all levels are fully filled except possibly the last level, which is filled from left
    15+ min read
    K-ary Heap
    Prerequisite - Binary Heap K-ary heaps are a generalization of binary heap(K=2) in which each node have K children instead of 2. Just like binary heap, it follows two properties: Nearly complete binary tree, with all levels having maximum number of nodes except the last, which is filled in left to r
    15 min read

    Easy problems on Heap

    Check if a given Binary Tree is a Heap
    Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).Every node’s v
    15+ min read
    How to check if a given array represents a Binary Heap?
    Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: ar
    11 min read
    Iterative HeapSort
    HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
    11 min read
    Find k largest elements in an array
    Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order.Examples:Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23]Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17]Table of Content[Nai
    15+ min read
    K’th Smallest Element in Unsorted Array
    Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
    15 min read
    Height of a complete binary tree (or Heap) with N nodes
    Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
    3 min read
    Heap Sort for decreasing order using min heap
    Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1}Output : arr[] = {10, 5, 3, 1}Input : arr[] = {1, 50, 100, 25}Output : arr[] = {100, 50, 25, 1}Prerequisite: Heap sort using min heap.Using Min Heap Implementation - O(n Log n) Time
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences