Advertisement
MELAMOURI

Untitled

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