Advertisement
GrandtherAzaMarks

MergeSort

Apr 5th, 2018
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <ctime>
  4. #include <cstdlib>
  5.  
  6.  
  7. using namespace std;
  8.  
  9.  
  10. void merge(vector<int>& v, int first1, int last1, int first2, int last2, vector<int>& tmp)
  11. {
  12.     int first = first1;
  13.     int last = last2;
  14.     int i = 0;
  15.     while (first1 != last1 && first2 != last2
  16.     {
  17.         if (v[first1] < v[first2])
  18.         {
  19.             tmp[i] = v[first1];
  20.             ++i;
  21.             ++first1;
  22.         }
  23.         else
  24.         {
  25.             tmp[i] = v[first2];
  26.             ++i;
  27.             ++first2;
  28.         }
  29.     }
  30.     while (first1 != last1)
  31.     {
  32.         tmp[i] = v[first1];
  33.         ++i;
  34.         ++first1;
  35.     }
  36.     while (first2 != last2)
  37.     {
  38.         tmp[i] = v[first2];
  39.         ++i;
  40.         ++first2;
  41.     }
  42.     i = 0;
  43.     while (first != last)
  44.     {
  45.         v[first] = tmp[i];
  46.         ++i;
  47.         ++first;
  48.     }
  49. }
  50.  
  51. void mergesort(vector<int>& v, int first, int last)
  52. {
  53.     if (last - first <= 1)
  54.         return;
  55.     vector<int> tmp(v.size());
  56.     mergesort(v, first, (first + last) / 2);
  57.     mergesort(v, (first + last) / 2, last);
  58.     merge(v, first, (first + last) / 2, (first + last) / 2, last, tmp);
  59. }
  60.  
  61. int main()
  62. {
  63.     srand(time(NULL));
  64.     vector<int> v(20);
  65.     for (int i = 0; i < 20; ++i)
  66.         v[i] = rand() % 100;
  67.     for (int i = 0; i < 20; ++i)
  68.         cout << v[i] << ' ';
  69.     cout << '\n';
  70.     mergesort(v, 0, 20);
  71.     for (int i = 0; i < 20; ++i)
  72.         cout << v[i] << ' ';
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement