Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. void heapify(int arr[], int n, int i)
  2. {
  3. int largest = i; // Initialize largest as root
  4. int l = 2 * i + 1; // left = 2*i + 1
  5. int r = 2 * i + 2; // right = 2*i + 2
  6.  
  7. // If left child is larger than root
  8. if (l < n && arr[l] > arr[largest])
  9. largest = l;
  10.  
  11. // If right child is larger than largest so far
  12. if (r < n && arr[r] > arr[largest])
  13. largest = r;
  14.  
  15. // If largest is not root
  16. if (largest != i)
  17. {
  18. swap(arr[i], arr[largest]);
  19.  
  20. // Recursively heapify the affected sub-tree
  21. heapify(arr, n, largest);
  22. }
  23. }
  24.  
  25. // main function to do heap sort
  26. void heapSort(int arr[], int n)
  27. {
  28. // Build heap (rearrange array)
  29. for (int i = n / 2 - 1; i >= 0; i--)
  30. heapify(arr, n, i);
  31.  
  32. // One by one extract an element from heap
  33. for (int i = n - 1; i >= 0; i--)
  34. {
  35. // Move current root to end
  36. swap(arr[0], arr[i]);
  37.  
  38. // call max heapify on the reduced heap
  39. heapify(arr, i, 0);
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement