Rakibul_Ahasan

Heap Sort

Oct 21st, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void heapify(int A[],int n,int i){
  5.     int largest=i;
  6.     int l=2*i;
  7.     int r=(2*i)+1;
  8.  
  9.     while(l<n && A[l]>A[largest]){
  10.         largest=l;
  11.     }
  12.  
  13.     while(r<n && A[r]>A[largest]){
  14.         largest=r;
  15.     }
  16.  
  17.     if(largest!=i){
  18.         swap(A[largest],A[i]);
  19.         heapify(A,n,largest);
  20.     }
  21. }
  22.  
  23. void heapsort(int A[],int n){
  24.     for(int i=n/2-1;i>=0;i--){
  25.         heapify( A,n,i);
  26.     }
  27.  
  28.     for(int i=n-1;i>=0;i--){
  29.         swap(A[0],A[i]);
  30.         heapify( A,i,0);
  31.     }
  32. }
  33.  
  34. void printArray(int A[], int n)
  35. {
  36.     for (int i=0; i<n; ++i)
  37.         cout << A[i] << " ";
  38.     cout << "\n";
  39. }
  40.  
  41. int main()
  42. {
  43.     int A[]={23,12,56,34,89,39};
  44.     int n=6;
  45.  
  46.     printArray(A,n);
  47.  
  48.     heapsort(A,n);
  49.  
  50.     cout << "\nSorted array is:\n";
  51.     printArray(A,n);
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment