Advertisement
Korotkodul

MergeSort

Oct 1st, 2023
712
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using std::cin;
  6. using std::cout;
  7. using std::max;
  8. using std::min;
  9. using std::string;
  10. using std::vector;
  11.  
  12. int inv = 0;
  13.  
  14. vector<int> MergeSort(vector<int> ar) {
  15.   int len = ar.size();
  16.   if (len == 1) {
  17.     return ar;
  18.   }
  19.   vector<int> lt;
  20.   vector<int> rt;
  21.   for (int id = 0; id < len / 2; ++id) {
  22.     lt.push_back(ar[id]);
  23.   }
  24.   for (int id = len / 2; id < len; ++id) {
  25.     rt.push_back(ar[id]);
  26.   }
  27.   lt = MergeSort(lt);
  28.   rt = MergeSort(rt);
  29.   int ln = lt.size();
  30.   int rn = rt.size();
  31.   int lid = 0;
  32.   int rid = 0;
  33.   vector<int> res;
  34.   while (lid < ln || rid < rn) {
  35.     if (lid < ln && rid < rn) {
  36.       if (lt[lid] <= rt[rid]) {
  37.         res.push_back(lt[lid]);
  38.         lid++;
  39.       } else {
  40.         res.push_back(rt[rid]);
  41.         rid++;
  42.         inv += ln - lid;
  43.       }
  44.     } else if (lid < ln) {
  45.       res.push_back(lt[lid]);
  46.       lid++;
  47.  
  48.     } else if (rid < rn) {
  49.       res.push_back(rt[rid]);
  50.       rid++;
  51.     }
  52.   }
  53.   return res;
  54. }
  55.  
  56. int main() {
  57.   std::ios::sync_with_stdio(false);
  58.   std::cin.tie(0);
  59.   std::cout.tie(0);
  60.   int len;
  61.   cin >> len;
  62.   vector<int> ar(len);
  63.   for (int& el : ar) {
  64.     cin >> el;
  65.   }
  66.   ar = MergeSort(ar);
  67.   /*for (int el: ar) {
  68.     cout << el << ' ';
  69.   }
  70.   cout << "\n";*/
  71.   cout << inv << "\n";
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement