×

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

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Extended Binary Tree

A form of binary tree known as an extended binary tree replaces all of the original tree's null subtrees with special nodes known as external nodes, while the remaining nodes...

4 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Function to Delete a Leaf Node from a Binary Tree

Implementation // We are writing a C++ code to eliminate all the leaves from the given value.  #include <bits/stdc++.h> using namespace std; // creating a new binary tree node struct __nod { int record; struct __nod *Lft,...

4 minutes read.

Treap data structure

In this article, we will discuss the treap data structure. The word treap is a combination of 'tree' and 'heap'. So, treap data structure is a combination of a heap...

8 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 minutes read.

B Tree in Data Structure

Data management is called database management. A data model is a system that stores, manages, and optimizes computer resources. Data processing is not just about data storage. Almost every app...

9 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Applications of trees in data structures

Data structures Storage used to organize and store data is known as the data structure. It is a method of managing computerized data to translate or retrieve it more efficiently. A...

7 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 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.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.