繁体   English   中英

C ++中的Mergesort实现错误

[英]Error with Mergesort implementation in C++

我正在学习实现用于计算反转的mergesort算法。 这是我当前对mergesort的实现。 但是,它不工作,因为它不返回已排序的数组。 谁能告诉我我编写的这段代码做错了什么? 它应该对输入到函数中的数组v进行排序。

void mergeCountInversion(vector<int> v, int l, int r)
{
    if (l >= r)
    {
        return;
    }

    int m = (l + r)/2;  

    //call merge sort to return two sorted arrays
    mergeCountInversion(v, l, m);
    mergeCountInversion(v, m+1, r);

    int left = l;
    int right = m+1;
    std::vector<int> vtemp ;

    //merge and sort the two sorted array, storing the sorted array in vtemp
    for (int k = l; k <= r; ++k){
        if (left >= m+1)
        {
            vtemp.push_back(v[right]);
            right++;
        }
        else if (right > r)
        {
            vtemp.push_back(v[left]);
            left++;
        }
        else
        {
            if (v[left] <= v[right])
            {
                vtemp.push_back(v[left]);
                left++;
            }
            else{
                vtemp.push_back(v[right]);
                right++;
                count += m + 1 - left;
            }
        }
    }

    //replace v with the sorted array vtemp
    for (int i = 0; i < vtemp.size(); ++i)
    {
        v[l+i] = vtemp[i];
    }
}

您定义

void mergeCountInversion(vector<int> v, int l, int r)

然后您首先mergeCountInversion递归方式调用mergeCountInversion ,然后在调用返回后修改v

问题在于,递归调用中对v所做的更改将永远不会被看到,因为v通过value传递的

尝试通过引用传递v

void mergeCountInversion(vector<int>& v, int l, int r)

这样所有调用都在v的相同副本上工作。

您的代码中有几个问题。

您正在按值传递向量,但应通过引用传递。

如果将函数声明为void则不能return 0;否则,不能return 0; ,只需return;

创建vtemp ,应该确切知道其大小:r-l。 因此,您可以为其保留内存,而无需push_back。

您也必须将计数传递给函数。

您的功能可以是:

void mergeCountInversion(vector<int> & v, int l, int r, int & count) {
    if (l >= r) return;

    int m = (l + r)/2;  

    //call merge sort to return two sorted arrays
    mergeCountInversion(v, l, m, count);
    mergeCountInversion(v, m+1, r, count);

    int left = l;
    int right = m+1;
    std::vector<int> vtemp(r-l);

    //merge and sort the two sorted array, storing the sorted array in vtemp
    for (int k = l; k <= r; ++k) {
        if (left >= m+1) {
            vtemp[k] = v[right];
            right++;
        }
        else if (right > r) {
            vtemp[k] =  v[left];
            left++;
        }
        else {
            if (v[left] <= v[right]) {
                vtemp[k] = v[left];
                left++;
            }
            else {
                vtemp[k] = v[right];
                right++;
                count += m + 1 - left;
            }
       }
    }

    //replace v with the sorted array vtemp
    for (int i = 0; i < vtemp.size(); ++i)
    v[l+i] = vtemp[i];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM