×

Heap Sort in Data Structure

Heap Sort

A heap is a tree-based data structure that has specific properties.

  • Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.
  • If the value placed in each node is greater than or equal to its two children, then that heap is called max heap.
  • If the value placed in each node is less than or equal to its two children, then that heap is called min-heap.
  • If you want to sort the list in ascending order (increasing order), then you create the min-heap.
  • If you want to sort the list in descending order (decreasing order), then you create the max heap.
Heap Sort in DS

Complexity table of Heap sort

ComplexityBest caseAverage caseWorst case
TimeO(nlogn)O(nlogn)O(nlogn)
Space  O(1)

Selection sort algorithm

Heapsort (A) 
Build_Max_heap(A)
for i ? length[A] down to 2
do exchange A[i] ? A[1]
heapsize(A) ? heapsize (A – 1)
Max_heapify (A, 1)  

This algorithm is for max heap sort.

Step 1: Create a new node.

Step 2: Assign a value to the node.

Step 3: Compare the value of the child node with the value of the parent node.

Step 4: If the child node value is greater than the parent node value, then interchange them. 

Step 5: Repeat steps 3 and 4 until the heap is sorted correctly.

Build_Max_heap(A)
heapsize(A) ? length[A]
for i ? length[A / 2] down to 1
Max_heapify (A, i)  
Max_heapify (A, i)
 l ? left[i]
r ? right[i]if l <= heapsize(A) and A[l] > A[i]
then largest ? l
also, largest ? iif r <= heapsize(A) and A[r] > A[largest]then largest ? rdo if i ? largestexchange A[i]  ? A[largest]Max_heapify (A, largest)  

Heap sort program in C language

#include<stdio.h>  
int val; 
void heapify(int arr[], int size, int i)
{      
int largest = i;       
int left = 2*i + 1;     
 int right = 2*i + 2;      
  if (left < size && arr[left] >arr[largest])         largest = left;      if (right < size && arr[right] > arr[largest])         largest = right;      if (largest != i)       
 {          
 val = arr[i];          
  arr[i]= arr[largest];        
     arr[largest] = val;         
   heapify(arr, size, largest);       
   }   
}     
 void heapSort(int arr[], int size) 
  {  
      int i;      
  for (i = size / 2 - 1; i >= 0; i--)      
 heapify(arr, size, i);      
  for (i=size-1; i>=0; i--)      
 {           
 val = arr[0];  
          arr[0]= arr[i];      
       arr[i] = val;         
   heapify(arr, i, 0);      
  }  
 }    
  void main() 
  {     
      int arr[] = {20, 50, 40, 10, 90, 80, 60, 70, 30, 100};   
        int i;     
      int size = sizeof(arr)/sizeof(arr[0]);   
       heapSort(arr, size);   
       printf("heap sorted elements\n");  
         for (i=0; i<size; ++i)      
    printf("%d\n",arr[i]);   }    

Output

heap sorted elements
10 
20 
30 
40 
50 
60 
70 
80 
90 
100  

Heap sort program in java language

public class HeapSort      
{       
public void sort(int arr[])       
  {            
int n = arr.length;        // Build max heap         
    for (int i = n / 2 - 1; i >= 0; i--)          
   {          
       heapify(arr, n, i);       
     }                // Heap sort     
 for (int i = n - 1; i >= 0; i--)    
   {       
    int temp = arr[0];    
    arr[0] = arr[i];    
    arr[i] = temp;             // Heapify root element        
 heapify(arr, i, 0);  
     }  
  } 
 void heapify(int arr[], int n, int i)
 {       // Find largest among root, left child and right child             
   int largest = i;     
    int l = 2 * i + 1;    
     int r = 2 * i + 2;   
      if (l < n && arr[l] > arr[largest])    largest = l;      
   if (r < n && arr[r] > arr[largest])   
      largest = r;            // Swap and continue heapifying if root is not largest        
 if (largest != i)      
   {          
  int swap = arr[i];   
         arr[i] = arr[largest];  
          arr[largest] = swap;    
       heapify(arr, n, largest);   
      }
 }              // Function to print an array       
 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 code   public static void main(String args[]) 
     {      
   int arr[] = { 20, 50, 40, 10, 90, 80, 60, 70, 30, 100 }; 
        HeapSort hs = new HeapSort();     
    hs.sort(arr);     
    System.out.println("heap sorted elements");   
      printArray(arr);   
   } 
}

Output

heap sorted elements 
10
20 
30 
40 
50 
60 
70 
80 
90 
100  

Related Topics

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Bubble Sort vs Heap Sort

In this article, we are going to compare the two most common sorting techniques, Bubble Sort and Heap sort. Before discussing their differences, let us first discuss the idea of...

7 minutes read.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space In this problem, we need to find the length of the longest palindrome list that is present in given...

2 minutes read.

Given a Binary Tree Return All Root-to-Leaf Paths

Implementation #include <bits/stdc++.h> using namespace std; // A binary tree node generally consists of data, a pointer to the left and right child, and a pointer to the right child.  class __nod { public: int record; __nod* Lft; __nod*...

9 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

What is B tree?

What do you mean by B Tree in Data Structures? In the technological world, a B tree is simply a well-managed and coordinated tree and an integral part of the data...

6 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

How to get Better in Data Structures and Algorithms?

Introduction Data structures and algorithms are fundamental computer science concepts that store, organize, and process data efficiently. By understanding different data structures and algorithms and using them effectively, you can become...

19 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Hashing and its Applications

Hashing Hashing refers to transforming plain text data in such a way that even if it is leaked for some reason, no one would be able to make sense of it....

6 minutes read.