Advertisement
Batisk_AFF

HeapSort

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