Heap Sort | Practice | GeeksforGeeks

Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.

Example 1:
Input:
N = 5
arr[] = {4,1,3,9,7}
Output:
1 3 4 7 9
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1,3,4,7,9.

Example 2:
Input:
N = 10
arr[] = {10,9,8,7,6,5,4,3,2,1}
Output:
1 2 3 4 5 6 7 8 9 10
Explanation:
After sorting elements
using heap sort, elements will be
in order as 1, 2,3,4,5,6,7,8,9,10.

Your Task :
You don't have to read input or print anything. Your task is to complete the functions heapify(), buildheap() and heapSort() where heapSort() and buildheap() takes the array and it's size as input and heapify() takes the array, it's size and an index i as input. Complete and use these functions to sort the array using heap sort algorithm.
Note: You don't have to return the sorted list. You need to sort the array "arr" in place.

Expected Time Complexity: O(N * Log(N)).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ N ≤ 106
1 ≤ arr[i] ≤ 106
0
rajeshbathula292 days ago
can any one send a C program that uses both stack and heap memories plsss
0
hharshit81182 weeks ago
class Solution{
public: 
 void heapify(int arr[], int n, int i)     {       int left = 2*i+1, right = 2*i+2;       int largest = i;       if(left < n && arr[left] > arr[i])           largest = left;       if(right < n && arr[largest] < arr[right])           largest = right;       if(largest != i){           swap(arr[i], arr[largest]);           heapify(arr, n, largest);       }   }
   public:   //Function to build a Heap from array.   void buildHeap(int arr[], int n)     {        for(int i = (n-2)/2; i >= 0; i--){           heapify(arr, n, i);       }   }
      public:   //Function to sort an array using Heap Sort.   void heapSort(int arr[], int n)   {       buildHeap(arr, n);       for(int i = n-1; i >= 0; i--){           swap(arr[0], arr[i]);           heapify(arr, i, 0);       }   }
};
-2
adarshgupta4011 month ago
Easy Java Soln-
class Solution
{
    //Function to build a Heap from array.
    void buildHeap(int arr[], int n)
    {
        //code
        for(int i = n/2 -1; i>=0; i--)
            heapify(arr, n, i);
    }
 
    //Heapify function to maintain heap property.
    void heapify(int arr[], int n, int i)
    {
        //code
        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;
        }
        if( largest != i){
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;
            
            heapify(arr, n, largest );
        }
    }
    
    //Function to sort an array using Heap Sort.
    public void heapSort(int arr[], int n)
    {
        //code here
        buildHeap(arr, n);
        for( int i = n-1; i>0; i--){
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            
            heapify(arr, i, 0);
        }
    }
 }
 
+1
gunjangoyal2821 month ago
class Solution:
    #Heapify function to maintain heap property.
    def heapify(self,arr, n, i):
        # code here
        largest = i
        l = 2*i + 1
        r = 2*i + 2
        if l < n and arr[l] > arr[largest]:
            largest = l
        if r < n and arr[r] > arr[largest]:
            largest = r
        if largest != i:
            arr[i],arr[largest] = arr[largest],arr[i]
            self.heapify(arr,n,largest)
    
    #Function to build a Heap from array.
    def buildHeap(self,arr,n):
        # code here
        idx = n//2 - 1
        for i in range(idx,-1,-1):
            self.heapify(arr,n,i)
    
    #Function to sort an array using Heap Sort.    
    def HeapSort(self, arr, n):
        #code here
        self.buildHeap(arr,n)
        for i in range(n-1,0,-1):
            arr[i],arr[0] = arr[0],arr[i]
            self.heapify(arr,i,0)
+1
sanketbhagat2 months ago
SIMPLE JAVA SOLUTION
class Solution{
    
    private void swap(int arr[], int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    //Function to build a Heap from array.
    void buildHeap(int arr[], int n){
        // Your code here
        int child = n;
        int par = (child-1)/2;
        while(child>0 && arr[par]<arr[child]){
            swap(arr,par,child);
            child = par;
            par = (child-1)/2;
        }
    }
 
    //Heapify function to maintain heap property.
    void heapify(int arr[], int n, int i){
        // Your code here
        swap(arr,0,n);
        int par = 0;
        int child1 = 1;
        int child2 = 2;
        while(child1<n){
            if(child2>=n){
                if(arr[par]<arr[child1]) swap(arr,par,child1);
                return;
            }
            if(arr[par]>arr[child1] && arr[par]>arr[child2]) return;
            if(arr[child1]>arr[child2]){
                swap(arr,par,child1);
                par = child1;
            }else{
                swap(arr,par,child2);
                par = child2;
            }
            child1 = 2*par+1;
            child2 = 2*par+2;
        }
    }
    
    //Function to sort an array using Heap Sort.
    public void heapSort(int arr[], int n){
        //code here
        for(int i=0;i<n;i++) buildHeap(arr,i);
        for(int i=0;i<n;i++) heapify(arr,n-i-1,i);
    }
 }
0
shilpfizzy2 months ago
 
class Solution{   public:   //Heapify function to maintain heap property.   void heapify(int arr[], int n, int i)     {    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;
      if (largest != i) {       swap(arr[i], arr[largest]);
              heapify(arr, n, largest);   }        }
   public:   //Function to build a Heap from array.   void buildHeap(int arr[], int n)     {      for(int i = n/2 - 1; i >= 0; i--){         heapify(arr,n,i);     }   }
      public:   //Function to sort an array using Heap Sort.   void heapSort(int arr[], int n)   {       buildHeap(arr,n);       for(int i = n-1; i > 0; i--){           swap(arr[0],arr[i]);           heapify(arr,i,0);       }   }};
+1
johnniehdk122 months ago
c++ solution
 
class Solution{   public:   //Heapify function to maintain heap property.   void heapify(int arr[], int n, int i)     {     // Your Code Here     int pospar = i;     int left, right;     while (pospar<n){         left = 2*pospar + 1;         right = 2*pospar + 2;         if (left<n && right<n){             if (arr[left]<=arr[right] && arr[left]<arr[pospar])             {                 swap(arr[left], arr[pospar]);                 pospar = left;             }             else if (arr[right]<=arr[left] && arr[right]<arr[pospar]){                  swap(arr[right], arr[pospar]);                  pospar = right;             }             else               break;         }         else if (left<n){             if (arr[left]<arr[pospar]){                 swap(arr[left], arr[pospar]);                 pospar = left;             }             else               break;         }         else           break;     }   }
   public:   //Function to build a Heap from array.   void buildHeap(int arr[], int n)     {    // Your Code Here       for (int i=n/2-1;i>=0;i--){           heapify(arr, n, i);       }   }
      public:   //Function to sort an array using Heap Sort.   void heapSort(int arr[], int n)   {       //code here       buildHeap(arr, n);       int arr2[n], size=0, length=n;       for (int i=0;i<n;i++)           arr2[i] = 0;       arr2[size] = arr[0];       size++;       length--;       if (length != 0){           arr[0] = arr[length];           int pospar=0;           while (length>0){              heapify(arr, length, pospar);              arr2[size] = arr[0];              size++;              length--;              if (length == 0)                 continue;              arr[0] = arr[length];           }             for (int i=0;i<n;i++)               arr[i] = arr2[i];       }                    }};
0
biniyamdemissew1122 months ago
ggjh
0
amitanand22 months ago
class Solution
{
    public:
    //Heapify function to maintain heap property.
    void heapify(int arr[], int n, int i)  
    {
      // Your Code Here
      int largest = i;
      int left = 2*largest+1;
      int  right = left + 1;
      
      if(left < n && arr[left] > arr[largest]){
          largest =  left;
      }
      if(right < n && arr[right] > arr[largest]){
          largest = right;
      }
      if(largest != i){
          swap(arr[largest] , arr[i]);
          heapify(arr , n , largest);
      }
      
    }

    public:
    //Function to build a Heap from array.
    void buildHeap(int arr[], int n)  
    { 
    // Your Code Here
    for(int i = (n-1)/2 ; i>= 0 ; i--){
        heapify(arr , n , i);
    }
    }

    
    public:
    //Function to sort an array using Heap Sort.
    void heapSort(int arr[], int n)
    {
        //code here
        buildHeap(arr , n);
        
        for(int i = n-1 ; i> 0 ; i--){
            swap(arr[0] , arr[i]);
            heapify(arr , i , 0);
        }
    }
};
0
vishalpandey100220002 months ago
void buildHeap(int arr[], int n)   {       // Your code here       for (int i=(n-2)/2;i>=0;i--){           heapify(arr,n,i);       }   }   //Heapify function to maintain heap property.   void heapify(int arr[], int n, int i)   {       // Your code here       int largest=i;       int lt=2*i+1;       int rt=2*i+2;       if (lt<n &&arr[lt]>arr[largest]){           largest=lt;        }       if (rt<n && arr[rt]>arr[largest]){           largest=rt;       }       if (largest!=i){           int temp=arr[largest];           arr[largest]=arr[i];           arr[i]=temp;           heapify(arr,n,largest);       }   }      //Function to sort an array using Heap Sort.   public void heapSort(int arr[], int n)   {       //code here       buildHeap(arr,n);       for (int i=n-1;i>=1;i--){           int temp=arr[0];           arr[0]=arr[i];           arr[i]=temp;           heapify(arr,i,0);       }   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.