大家好我正在努力实现合并排序算法,我已经让我的代码工作了,但我的工作仍然有问题。例如,当我输入“1 3 5 2”时,我收到“1 3 5 5”。我想帮助找到我的错误,因为即使使用cerr语句我也无法这样做。谢谢
vector<int> VectorOps::mergeSort(vector<int> toSort)
{
if (toSort.size() <= 1)
{
return toSort;
}
std::vector<int>::iterator middle = toSort.begin() + (toSort.size() / 2);
vector<int> left(toSort.begin(), middle);
vector<int> right(middle, toSort.end());
left = mergeSort(left);
right = mergeSort(right);
cerr << "The numbers are "<< endl;
return merge(left, right);
}
vector<int> merge(const vector<int>& left, const vector<int>& right)
{
vector<int> toReturn;
unsigned left_it = 0, right_it = 0;
while(left_it < left.size() && right_it < right.size())
{
if(left[left_it] < right[right_it])
{
toReturn.push_back(left[left_it]);
left_it++;
}
else
{
toReturn.push_back(left[left_it]);
right_it++;
}
}
while(left_it < left.size())
{
toReturn.push_back(left[left_it]);
left_it++;
}
while(right_it < right.size())
{
toReturn.push_back(right[right_it]);
right_it++;
}
return toReturn;
}
答案 0 :(得分:4)
在merge
的第一个条件中,两个分支都有
toReturn.push_back(left[left_it]);
其中一个应该是
toReturn.push_back(right[right_it]);
这就是复制和粘贴被认为有害的原因。
答案 1 :(得分:0)
将toReturn.push_back(left[left_it]);
更改为toReturn.push_back(left[right_it]);