Advertisement
avisrivastava254084

Untitled

Dec 1st, 2019
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. //
  2. // Created by Gowtham Asokan on 12/1/19.
  3. //
  4.  
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9. // To heapify a subtree rooted with node i which is
  10. // an index in arr[]. n is size of heap
  11. void heapify(int arr[], int n, int i)
  12. {
  13.     int largest = i; // Initialize largest as root
  14.     int l = 2*i + 1; // left = 2*i + 1
  15.     int r = 2*i + 2; // right = 2*i + 2
  16.  
  17.     // If left child is larger than root
  18.     if (l < n && arr[l] > arr[largest])
  19.         largest = l;
  20.  
  21.     // If right child is larger than largest so far
  22.     if (r < n && arr[r] > arr[largest])
  23.         largest = r;
  24.  
  25.     // If largest is not root
  26.     if (largest != i)
  27.     {
  28.         swap(arr[i], arr[largest]);
  29.  
  30.         // Recursively heapify the affected sub-tree
  31.         heapify(arr, n, largest);
  32.     }
  33. }
  34.  
  35. /* A utility function to print array of size n */
  36. void printArray(int arr[], int n)
  37. {
  38.     cout << 'inside print array' << endl;
  39.     for (int i=0; i<n; ++i)
  40.         cout << arr[i] << " ";
  41.     cout << "\n";
  42. }
  43.  
  44. // main function to do heap sort
  45. void heapSort(int arr[], int n)
  46. {
  47.     // Build heap (rearrange array)
  48.     for (int i = n / 2 - 1; i >= 0; i--)
  49.         heapify(arr, n, i);
  50.  
  51.     // One by one extract an element from heap
  52.     for (int i=n-1; i>=0; i--)
  53.     {
  54.         // Move current root to end
  55.         swap(arr[0], arr[i]);
  56.  
  57.         // call max heapify on the reduced heap
  58.         heapify(arr, i, 0);
  59.     }
  60.     // printArray(arr, n);
  61. }
  62.  
  63.  
  64. // Driver program
  65. int main()
  66. {
  67.     int num;
  68.     int arr[5];
  69.     cout << "Please enter your numbers one at a time, press ctrl-z to end: " << endl;
  70.     for (int z = 0; z < 5;z++) {
  71.         cin >> num;
  72.         arr[z] = num;
  73.     }
  74.  
  75.     int n = sizeof(arr)/sizeof(arr[0]);
  76.  
  77.     heapSort(arr, n);
  78.  
  79.     cout << "Sorted array is" << endl;
  80.     printArray(arr, n);
  81.  
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement