Compiles and don't see any logic issues..but the vector will not sort.
#include<iostream>
#include<vector>
#include<cstdlib>
#include<iterator>
using namespace std;
vector<int> merge(const vector<int>& left, const vector<int>& right);
vector<int> merge_sort(vector<int>& vec);
int main(){
vector<int> vec{9,3,7,4,8,5,1,2,6,0};
cout << "The vector, before recursive merge sort:" << endl;
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl << endl;
merge_sort(vec);
cout << "The vector, after recursive merge sort:" << endl;
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << ' ';
cout << endl << endl;
return 0;
}
vector<int> merge(const vector<int>& left, const vector<int>& right){
vector<int> result;
unsigned left_it = 0, right_it = 0;
while(left_it < left.size() && right_it < right.size()){
if(left[left_it] < right[right_it]){
result.push_back(left[left_it]);
left_it++;
}
else{
result.push_back(right[right_it]);
right_it++;
}
}
while(left_it < left.size()){
result.push_back(left[left_it]);
left_it++;
}
while(right_it < right.size()){
result.push_back(right[right_it]);
right_it++;
}
return result;
}
vector<int> merge_sort(vector<int>& vec){
if(vec.size() == 1)
{
return vec;
}
vector<int>::iterator middle = vec.begin() + (vec.size() / 2);
vector<int> left(vec.begin(), middle);
vector<int> right(middle, vec.end());
left = merge_sort(left);
right = merge_sort(right);
return merge(left, right);
}
OUTPUT:
The vector, before recursive merge sort:
9 3 7 4 8 5 1 2 6 0
The vector, after recursive merge sort:
9 3 7 4 8 5 1 2 6 0
Program ended with exit code: 0
Mine won't compile now. I'm receiving this error message:
No viable conversion from'_wrap_iter<const int *>'to'_wrap_iter<pointer>'
Right here:
vector<int> merge_sort(const vector<int>& vec){
if(vec.size() == 1)
{
return vec;
}
vector<int>::iterator middle = vec.begin() + (vec.size() / 2);
vector<int> left(vec.begin(), middle);
vector<int> right(middle, vec.end());
left = merge_sort(left);
right = merge_sort(right);
return merge(left, right);
}
vector<int>::const_iterator middle
Ah geez. Right. Okay, still no sorting though..
you are doing merge_sort(vec);
`merge_sort()' receives a constant reference, so its argument remains unchanged. Your statement has no effect.
Note that you also aren't catching the returned value.
Thanks a lot ne555!
Last edited on