Advertisement
GrandtherAzaMarks

Heap (Heap Sort)

Apr 7th, 2018
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void rep(vector <int>& v, int p, int top)
  7. {
  8.     int l = 2 * p + 1;
  9.     int r = 2 * p + 2;
  10.     if (top <= l)
  11.         return;
  12.     if (top == l + 1)
  13.         r = l;
  14.     int imax = v[l] > v[r] ? l : r;
  15.     if (v[imax] > v[p])
  16.         swap(v[imax], v[p]);
  17.     rep(v, imax, top);
  18. }
  19.  
  20. int main()
  21. {
  22.     vector <int> a;
  23.     for (int i = 0; i < 10; i++)
  24.     {
  25.         a.push_back(i);
  26.         cout << a[i] << " ";
  27.     }
  28.     cout << endl;
  29.    
  30.     for (int i = (int)a.size() / 2; i >= 0; i--)
  31.         rep(a, i, (int)a.size());
  32.    
  33.     for (int i = 0; i < 10; i++)
  34.         cout << a[i] << " ";
  35.     cout << endl;
  36.    
  37.     for (int i = (int)a.size() - 1; i > 0; i--)
  38.     {
  39.         swap(a[0], a[i]);
  40.         rep(a, 0, i);
  41.     }
  42.    
  43.     for (int i = 0; i < 10; i++)
  44.         cout << a[i] << " ";
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement