Advertisement
Korotkodul

MERGE_SORT_OK

Sep 17th, 2022 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <string>
  7. #include <stack>
  8. #include <set>
  9. #include <map>
  10. #define pii pair <int, int>
  11. #define pb(x) push_back(x)
  12. using namespace std;
  13. using ll = long long;
  14. using ld = long double;
  15. using db = double;
  16. void cv(vector <int> &v) {
  17.     for (auto x : v) cout << x << ' ';
  18.     cout << "\n";
  19. }
  20.  
  21. void cvl(vector <ll> &v) {
  22.     for (auto x : v) cout << x << ' ';
  23.     cout << "\n";
  24. }
  25.  
  26.  
  27. void cvv(vector <vector <int> > &v) {
  28.     for (auto x : v) cv(x);
  29.     cout << "\n";
  30. }
  31.  
  32. void cvb(vector <bool> v) {
  33.     for (bool x : v) cout << x << ' ';
  34.     cout << "\n";
  35. }
  36.  
  37. void cvs(vector <string>  v) {
  38.     for (auto a : v) {
  39.         cout << a << "\n";
  40.     }
  41. }
  42.  
  43. void cvp(vector <pii> a) {
  44.     for (auto p : a) {
  45.         cout << p.first << ' ' << p.second << "\n";
  46.     }
  47.     cout << "\n";
  48. }
  49.  
  50. bool sh = 0;
  51. vector <int> a;
  52. void mrg(int l, int m, int r) {
  53.     vector <int> res;
  54.  
  55.     int A = l, B = m + 1;
  56.     while (A <= m && B <= r) {
  57.         if (a[A] < a[B]) {
  58.             res.pb(a[A]);
  59.             A++;
  60.         } else {
  61.             res.pb(a[B]);
  62.             B++;
  63.         }
  64.     }
  65.     while (A <= m) {
  66.         res.pb(a[A]);
  67.         A++;
  68.     }
  69.     while (B <= r) {
  70.         res.pb(a[B]);
  71.         B++;
  72.     }
  73.     for (int i = l; i <= r; ++i) {
  74.         a[i] = res[i - l];
  75.     }
  76. }
  77.  
  78. void f(int l, int r) {
  79.     if (l == r) {
  80.         return;
  81.     } else if (l + 1 == r) {
  82.         if (a[l] > a[r]) swap(a[l], a[r]);
  83.         return;
  84.     }
  85.  
  86.     int m = (l + r) / 2;
  87.  
  88.     f(l, m);
  89.  
  90.     f(m + 1, r);
  91.     mrg(l, m, r);
  92. }
  93.  
  94. /*
  95. 5
  96. 5 4 3 2 1
  97. */
  98.  
  99. int main() {
  100.     /*ios::sync_with_stdio(0);
  101.     cin.tie(0);
  102.     cout.tie(0);*/
  103.     int n; cin >> n;
  104.     a.resize(n);
  105.     for (int &i : a) cin >> i;
  106.  
  107.     f(0, n - 1);
  108.     cv(a);
  109. }
  110.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement