Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <ctime>
- #include <cstdlib>
- using namespace std;
- void merge(vector<int>& v, int first1, int last1, int first2, int last2, vector<int>& tmp)
- {
- int first = first1;
- int last = last2;
- int i = 0;
- while (first1 != last1 && first2 != last2
- {
- if (v[first1] < v[first2])
- {
- tmp[i] = v[first1];
- ++i;
- ++first1;
- }
- else
- {
- tmp[i] = v[first2];
- ++i;
- ++first2;
- }
- }
- while (first1 != last1)
- {
- tmp[i] = v[first1];
- ++i;
- ++first1;
- }
- while (first2 != last2)
- {
- tmp[i] = v[first2];
- ++i;
- ++first2;
- }
- i = 0;
- while (first != last)
- {
- v[first] = tmp[i];
- ++i;
- ++first;
- }
- }
- void mergesort(vector<int>& v, int first, int last)
- {
- if (last - first <= 1)
- return;
- vector<int> tmp(v.size());
- mergesort(v, first, (first + last) / 2);
- mergesort(v, (first + last) / 2, last);
- merge(v, first, (first + last) / 2, (first + last) / 2, last, tmp);
- }
- int main()
- {
- srand(time(NULL));
- vector<int> v(20);
- for (int i = 0; i < 20; ++i)
- v[i] = rand() % 100;
- for (int i = 0; i < 20; ++i)
- cout << v[i] << ' ';
- cout << '\n';
- mergesort(v, 0, 20);
- for (int i = 0; i < 20; ++i)
- cout << v[i] << ' ';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement