jayati

Heap Sort

Dec 3rd, 2023
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. //{ Driver Code Starts
  2. // C++ program for implementation of Heap Sort
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6.  
  7. // } Driver Code Ends
  8. // The functions should be written in a way that array become sorted
  9. // in increasing order when heapSort() is called.
  10.  
  11. class Solution
  12. {
  13.     public:
  14.     //Heapify function to maintain heap property.
  15.     void heapify(int arr[], int n, int i)  
  16.     {
  17.         int largest = i;
  18.         int left = 2*i + 1;
  19.         int right = 2*i + 2;
  20.         if(left<n&&arr[left]>arr[largest])
  21.         {
  22.             largest = left;
  23.         }
  24.         if(right<n&&arr[right]>arr[largest])
  25.         {
  26.             largest = right;
  27.         }
  28.         if(i!=largest)
  29.         {
  30.             swap(arr[i],arr[largest]);
  31.             heapify(arr,n,largest);
  32.         }
  33.         return;
  34.     }
  35.  
  36.     public:
  37.     //Function to build a Heap from array.
  38.     void buildHeap(int arr[], int n)  
  39.     {
  40.    
  41.         for(int i = n/2-1;i>=0;i--)
  42.         {
  43.             heapify(arr,n,i);
  44.         }
  45.     }
  46.  
  47.    
  48.     public:
  49.     //Function to sort an array using Heap Sort.
  50.     void heapSort(int arr[], int n)
  51.     {
  52.         buildHeap(arr,n);
  53.         for(int i = n-1;i>0;i--)
  54.         {
  55.             swap(arr[0],arr[i]);
  56.             heapify(arr,i,0);
  57.         }
  58.     }
  59. };
  60.  
  61.  
  62.  
  63.  
  64. //{ Driver Code Starts.
  65.  
  66. /* Function to print an array */
  67. void printArray(int arr[], int size)
  68. {
  69.     int i;
  70.     for (i=0; i < size; i++)
  71.         printf("%d ", arr[i]);
  72.     printf("\n");
  73. }
  74.  
  75. // Driver program to test above functions
  76. int main()
  77. {
  78.     int arr[1000000],n,T,i;
  79.     scanf("%d",&T);
  80.     while(T--){
  81.     scanf("%d",&n);
  82.     for(i=0;i<n;i++)
  83.       scanf("%d",&arr[i]);
  84.     Solution ob;
  85.     ob.heapSort(arr, n);
  86.     printArray(arr, n);
  87.     }
  88.     return 0;
  89. }
  90.  
  91. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment