I'm trying to implement a merge sort function and I'm getting a compiler error that says "no match for 'operator=' " It occurs on my recursive assignment of left_list = mergesort(left_list) and the same error in the following line using right_list.
It compiles correctly if I take out the assignment and just have mergesort(left_list) but then it doesn't sort correctly. I thought that the way I have it now should merge sort correctly, but given that it doesn't, either the error has something to do with those lines or it's elsewhere in the mergesort() or merge() function.
Any help would be appreciated.
EDIT: I should add that this is a homework assignment and I was required to implement the code inside the function so the function "mergesort" is void even though I think it should return a vector, but my professor's online unit test grading system is counting on the fact that the function is "void"...
void mergesort(vector<int> &data) {
vector<int> left_list;
vector<int> right_list;
if ( data.size() <= 1 ) {
return;
}
// creates a middle point to separate into 2 sub lists
int middle = ( data.size() / 2 );
// create a list of elements to the left of middle
for ( int i = 0; i < middle; i++ ) {
left_list.push_back(data[i]);
}
// create a list of elements to the right of middle
for ( unsignedint i = middle; i < data.size(); i++ ) {
right_list.push_back(data[i]);
}
// break down the sub lists until they are of size 1
left_list = mergesort(left_list);
right_list = mergesort(right_list);
// merge the sublists in the correct order
merge(left_list, right_list);
}
vector<int> merge(vector<int> &left, vector<int> &right) {
vector<int> result;
unsigned left_it = 0;
unsigned right_it = 0;
while( left_it < left.size() && right_it < right.size() ) {
// the smaller value is put into the result vector
if( left[left_it] < right[right_it] ) {
result.push_back(left[left_it]);
left_it++;
}
else
{
result.push_back( right[right_it] );
right_it++;
}
}
// Put the rest of the data from both vectors onto result
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;
}