Advertisement
smatskevich

MergeSort

Nov 14th, 2022
712
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. // Слияние
  5. void Merge(std::vector<int>& v, int l, int m, int r) {
  6.   std::vector<int> result(r - l);
  7.   int i = l;
  8.   int j = m;
  9.   while (i < m && j < r) {
  10.     if (!(v[j] < v[i])) {
  11.       result[i - l + j - m] = v[i]; ++i;
  12.     } else {
  13.       result[i - l + j - m] = v[j]; ++j;
  14.     }
  15.   }
  16.   for (; i < m; ++i) result[i - l + j - m] = v[i];
  17.   for (; j < r; ++j) result[j - l] = v[j];
  18.   for (int k = 0; k < result.size(); ++k) v[l + k] = result[k];
  19. }
  20.  
  21. // Сортировка на диапазоне [l, r)
  22. void MergeSort(std::vector<int>& v, int l, int r) {
  23.   if (r - l <= 1) return;
  24.   int med = (r + l) / 2;
  25.   MergeSort(v, l, med);
  26.   MergeSort(v, med, r);
  27.   Merge(v, l, med, r);
  28. }
  29.  
  30. void MergeSort(std::vector<int>& v) {
  31.   MergeSort(v, 0, v.size());
  32. }
  33.  
  34. int main() {
  35.   int n = 0;
  36.   std::cin >> n;
  37.   std::vector<int> v(n);
  38.   for (int& x : v) std::cin >> x;
  39.   MergeSort(v);
  40.   for (int x : v) std::cout << x << " ";
  41.   return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement