c++ - 合并排序中的奇怪错误

标签 c++ mergesort divide-and-conquer

我刚刚在 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函数的问题,我不能对vector使用void函数还是别的什么。

真的希望有人能帮帮我。谢谢!

最佳答案

这是因为您按值 传递 vector ,这意味着您修改了本地拷贝。而是通过引用传递它。

关于c++ - 合并排序中的奇怪错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18813980/

相关文章:

c++ - char* 丢失数据

具有计算器错误的 Java Mergesort 实现

c - 将带链表的归并排序从 C 翻译成 MIPS

python - 在 O(lg n) 中查找 Python 列表的唯一数字对中的单个数字

java - 分而治之 : computing the time elapsed

c++ - 链表C++中的赋值运算符

c++ - 在循环内声明静态和非静态变量

php - 从 PHP 安全地编译、运行和返回 C++ 程序的输出

c++ - 在 C++ 中使用 vector 合并排序

performance - 算法 : how do divide-and-conquer and time complexity O(nlogn) relate?