Open In App

Iterative HeapSort

Last Updated : 29 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
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 =
      
            # 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)



Previous Article
Next Article

Similar Reads

Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Iterative Method to find Height of Binary Tree
There are two conventions to define the height of a Binary Tree Number of nodes on the longest path from the root to the deepest node. Number of edges on the longest path from the root to the deepest node. In this post, the first convention is followed. For example, the height of the below tree is 3. The recursive method to find the height of the B
8 min read
Iterative Search for a key 'x' in Binary Tree
Given a Binary Tree and a key to be searched in it, write an iterative method that returns true if key is present in Binary Tree, else false. For example, in the following tree, if the searched key is 3, then function should return true and if the searched key is 12, then function should return false. One thing is sure that we need to traverse comp
14 min read
C Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. C/C++ Code /* Recursive C program for merge sort */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* Function to merge the two haves arr[l..m] and arr[m+1..r] of array arr[] */ void merge(int arr[], int l, int m, int r); /* l is for left index and r
3 min read
Java Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Java Code // Recursive Java Program for merge sort import java.util.Arrays; public class GFG { public static void mergeSort(int[] array) { if(array == null) { return; } if(array.length &amp;gt; 1) { int mid = array.length / 2; // Split left part int[] lef
2 min read
Python Program for Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort that uses last element as pivot. Python] Python Program for Iterative Merge SortThe provided Python code demonstrates the recursive implementation of the Merge Sort algorithm. Merge Sort divides an array into smaller subarrays, sorts them, and then merges them back together to achieve a
2 min read
C Program for Iterative Quick Sort
C/C++ Code // An iterative implementation of quick sort #include &amp;lt;stdio.h&amp;gt; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function is same in both iterative and recursive*/ int partition(int arr[], int l, int h) { int x = arr[h]; int i = (l - 1); for (int j = l; j &amp;lt;
4 min read
Print all subsequences of a string | Iterative Method
Given a string s, print all possible subsequences of the given string in an iterative manner. We have already discussed Recursive method to print all subsequences of a string. Examples: Input : abc Output : a, b, c, ab, ac, bc, abc Input : aab Output : a, b, aa, ab, aab Approach 1 : Here, we discuss much easier and simpler iterative approach which
15 min read
Largest number less than or equal to N in BST (Iterative Approach)
We have a binary search tree and a number N. Our task is to find the greatest number in the binary search tree that is less than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: For the above given binary search tree- Input : N = 24 Output :result = 21 (searching for 24 will be like-5-&gt;12-&gt;21) Input : N
7 min read
Iterative Fast Fourier Transformation for polynomial multiplication
Given two polynomials, A(x) and B(x), find the product C(x) = A(x)*B(x). In the previous post, we discussed the recursive approach to solve this problem which has O(nlogn) complexity. Examples: Input : A[] = {9, -10, 7, 6} B[] = {-5, 4, 0, -2} Output : C(x) = [Tex]-12x^6 -14x^5 +44x^4 -20x^3 - 75x^2 +86x -45[/Tex] In real-life applications such as
12 min read
Article Tags :
Practice Tags :