简体   繁体   English

在 C++ 中的合并排序中传递数组时出错

[英]Error while passing array in merge sort in C++

I am trying to implement a merge sort algorithm in c++ but I keep getting a compilation error which I am to unable to overcome.我正在尝试在 C++ 中实现合并排序算法,但我不断收到无法克服的编译错误。

Here is the code这是代码

#include <bits/stdc++.h>
using namespace std;

void sort(int a[],int l,int r,int b[]){

    int mid=(l+r)/2;
    int L[mid-l],R[r-mid];
    if((r-l)==1)
    b[0]=a[l];
    else if((r-l)>1){

        sort(a,l,mid,L);
        sort(a,mid,r,R);
        merge(L,(mid-l),R,(r-mid),b);
    }

    return;
}

void merge(int a[],int n,int b[],int m,int c[]){

    int i=0,j=0,k=0;
    while(k<(m+n)){
        if(j==m||(a[i]<=b[j]&&i<n)){
            c[k]=a[i];
            i++;
            k++;
        }
        else if(i==n||(b[j]<a[i]&&j<m)){
            c[k]=b[j];
            j++;  
            k++;
        }
    }

    return;
}

int main(){

    int n;
    cin>>n;
    int a[n],b[n];
    int i;
    for(i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a,0,n,b);
    for(i=0;i<n;i++){
        cout<<b[i]<<" ";
    }
    return 0;
}

The error I keep getting is that I can't pass the array b[] from sort function to merge function.我不断收到的错误是我无法将数组 b[] 从排序函数传递到合并函数。

Please help me correct the problem.请帮我纠正问题。 Thanks in advance.提前致谢。

You need to declare merge before calling it.您需要在调用之前声明merge That means, you need to declare it before sort .这意味着,您需要在sort之前声明它。 For example -例如 -

void merge(int a[],int n,int b[],int m,int c[]);

Write this declaration before the definition of sortsort的定义之前写这个声明

EDIT I just figured out another error in this line编辑我刚刚发现这一行中的另一个错误

int a[n],b[n]

You cannot do this.你不可以做这个。 In C++ the size of array must be a compile time constant.在 C++ 中,数组的大小必须是编译时常量。

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

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