【问题标题】:Weird bug in mergesort合并排序中的奇怪错误
【发布时间】:2013-09-19 18:35:06
【问题描述】:

我刚刚在 mergesort 中编写了以下简单的合并函数,它与 CLRS 书中所写的完全一致。

#include<iostream>
#include<vector>
#include<limits>

using namespace std;

//Define the numerical positive infinity
const int INFP = numeric_limits<int>::max();

void MERGE(vector<int> A, int p, int q, int r){
    //Create the size of left and right array
    int n1 = q-p+1;
    int n2 = r-q;
    //Create the left array
    vector<int> L(n1+1);
    for(int i=0; i<n1;i++){
        L[i] = A[i];
    }
    L[n1] = INFP; //Insert sentinel here!
    //Create the right array
    vector<int> R(n2+1);
    for(int i=0; i<n2;i++){
        R[i] = A[q+i+1];
    }
    L[n2] = INFP; //Insert sentinel here!
    int i = 0;
    int j = 0;
    for(int k = 0; k <= r; k++){
        if(L[i]<=R[j]){
            A[k] = L[i];
            i=i+1;
        }
        else{
            A[k] = R[j];
            j=j+1;
        }
    }
    for(int m=0;m<4;m++){
        cout<< A[m] << " ";
    }
    cout << endl;
}

int main(){
    //test for merge function:
    vector<int> A(4);
    A[0]=1;
    A[1]=3;
    A[2]=2;
    A[3]=4;
    MERGE(A,0,1,3);
    for(int m=0;m<4;m++){
        cout<< A[m] << " ";
    }
    cout << endl;
    return 0;
}

但是,它给了我以下打印输出,这让我很困惑:

1 2 3 4
1 3 2 4

不知道是不是void函数的问题,我不能用void函数做vector之类的。

真的希望有人可以帮助我。谢谢!

【问题讨论】:

  • 注意:我可以告诉你一个“错误”。您正在按值传递向量。即使您的代码有效,caller 也不会看到您的劳动成果。并且您可以使用std::merge 和/或std::inplace_merge 使您的算法变得更加容易。事实上,它变得非常简单。

标签: c++ mergesort divide-and-conquer


【解决方案1】:

这是因为你传递了向量按值,意思是你修改了一个本地副本。而是通过引用传递它。

【讨论】:

  • 你能给我一个例子如何通过引用传递它吗?谢谢!
  • @Cancan 不,任何关于 C++ 语言的初学者书籍或教程都应该非常清楚地解释这一点。如果你没有,here is a good list.
  • 好吧,刚刚意识到我太懒了,但我已经想通了。谢谢!
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多