I am implementing a merge sort algorithm and I am receiving an std::bad_alloc in the merge algorithm and using the cerr statement I have found that my error is in first loop of the merge algorithm. However I am unable to figure out what is wrong.
vector<int> VectorOps::mergeSort(vector<int> toSort)
{
if(toSort.size() <= 1)
{
return toSort;
}
vector<int> left;
vector<int> right;
int half = toSort.size()/2;
for(int i = 0; i < half; ++i)
{
left.push_back(toSort.at(i));
}
for(int i = half; i < toSort.size(); ++i)
{
right.push_back(toSort.at(i));
}
//merge algorithim
vector<int> toReturn;
while(left.size() > 0 || right.size() > 0)
{
cerr << "The numbers are "<< endl;
if(left.size() > 0 && right.size() > 0)
{
if(left.at(0) <= right.at(0))
{
toReturn.push_back(left.at(0));
}
else
{
toReturn.push_back(right.at(0));
}
}
else if(left.size() > 0)
{
toReturn.push_back(left.at(0));
}
else if(right.size() > 0)
{
toReturn.push_back(right.at(0));
}
}
return toReturn;
}
cerrdoes not allow you to single step execution and look at variables.