dzungchaos

CTDL&TT: Heap Sort

Jul 5th, 2020
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <iostream>
  2. #include <conio.h>
  3.  
  4. void Swap(int& a, int& b)
  5. {
  6.   int temp = a;
  7.   a = b;
  8.   b = temp;
  9. }
  10.  
  11.  
  12. void ImplHeapify(int arr[], int n, int i)
  13. {
  14.   int root = i;
  15.   int l = 2*i + 1;  // left position = 2*i + 1
  16.   int r = 2*i + 2;  // right position = 2*i + 2
  17.  
  18.   // If left child is larger than root
  19.   if (l < n && arr[l] > arr[root])
  20.     root = l;
  21.  
  22.   // If right child is larger than largest so far
  23.   if (r < n && arr[r] > arr[root])
  24.     root = r;
  25.  
  26.   // If root position is not largest value
  27.   if (root != i)
  28.   {
  29.     Swap(arr[i], arr[root]);
  30.     ImplHeapify(arr, n, root);
  31.   }
  32. }
  33.  
  34. void ImplHeapSort(int arr[], int n)
  35. {
  36.   for (int i = (n/2) - 1; i >= 0; i--)
  37.     ImplHeapify(arr, n, i);
  38.  
  39.   for (int i = n-1; i >= 0; i--)
  40.   {
  41.     Swap(arr[0], arr[i]);
  42.     ImplHeapify(arr, i, 0);
  43.   }
  44. }
  45.  
  46. void Show(int arr[], int n)
  47. {
  48.   for (int i = 0; i < n; ++i)
  49.     std::cout << arr[i] << " ";
  50. }
  51.  
  52. int main()
  53. {
  54.   int arr[] = {12, 11, 13, 5, 6, 7};
  55.   int n = sizeof(arr)/sizeof(arr[0]);
  56.  
  57.   ImplHeapSort(arr, n);
  58.  
  59.   std::cout << "Sorted List is \n";
  60.   Show(arr, n);
  61.  
  62.   _getch();
  63. }
Advertisement
Add Comment
Please, Sign In to add comment