实现合并排序算法问题

时间:2014-01-06 21:30:17

标签: c++

我正在实现一个合并排序算法,我在合并算法中收到一个std :: bad_alloc,并使用cerr语句我发现我的错误是在合并算法的第一个循环中。但是我无法弄清楚出了什么问题。

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;
}

2 个答案:

答案 0 :(得分:1)

在:

while(left.size() > 0 || right.size() > 0)

leftright的大小永远不会改变(你不会删除头部元素)所以toReturn无限制地增长并且你的内存不足。

答案 1 :(得分:0)

正如@BenJackson在答案中已经提到的那样......

leftright的大小永远不会改变。您只需从向量中获取元素,而不是从中删除。因此,toReturn的大小无限增长。

vector没有删除头元素的任何方法但你可以实现像

left.erase(left.begin());

对于您的解决方案,要么从向量中移除头元素,要么只迭代向量并获取值。

vector<int> toReturn;
int l = 0; r = 0;
while (l < left.size() || r < right.size()) {

    if (l < left.size() && r < right.size()) {
        if (left.at(l) <= right.at(r)) {
            toReturn.push_back(left.at(l++));
        } else {
            toReturn.push_back(right.at(r++));
        }
    } else if (l < left.size()) {
        toReturn.push_back(left.at(l++));
    } else if (r < right.size()) {
        toReturn.push_back(right.at(r++));
    }
}

通过删除head元素合并实现。

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));

            //erase head element from left
            left.erase(left.begin());

        } else {
            toReturn.push_back(right.at(0));

            //erase head element from right
            right.erase(right.begin());

        }
    } else if (left.size() > 0) {
        toReturn.push_back(left.at(0));

        //erase head element from left
        left.erase(left.begin());
    } else if (right.size() > 0) {
        toReturn.push_back(right.at(0));

        //erase head element from right
        right.erase(right.begin());
    }
}