1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <vector>
using namespace std;
vector<int> merge(vector<int> left, vector<int> right) {
size_t ileft = 0, iright = 0;
vector<int> results;
while (ileft < left.size() && iright < right.size())
if (left[ileft] < right[iright])
results.push_back(left[ileft++]);
else
results.push_back(right[iright++]);
while (ileft < left.size() ) results.push_back(left [ileft++ ]);
while (iright < right.size()) results.push_back(right[iright++]);
return results;
}
vector<int> mergeSort(vector<int>& arr) {
if (arr.size() <= 1)
return arr;
int len = arr.size() / 2;
vector<int> left (arr.begin(), arr.begin() + len);
vector<int> right(arr.begin() + len, arr.end() );
return merge(mergeSort(left), mergeSort(right));
}
int main() {
vector<int> checkVal = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
vector<int> inputTest = { 15,12,13,11,9,10,7,8,14,6,5,3,4,2,1 };
vector <int> tempTest = mergeSort(inputTest);
if (tempTest == checkVal)
cout << "Sorted\n";
else
cout << "Not sorted\n";
for (int n: tempTest) cout << n << ' '; cout << '\n';
}
|