【问题标题】:Wrong output when i run with this Merge sort code使用此合并排序代码运行时输出错误
【发布时间】:2019-03-17 07:58:49
【问题描述】:

我已经实现了归并排序算法。我正确调试了代码。 但无法确定我的代码有什么问题。 这是我的代码:

#include<iostream>
using namespace std;
void merge(int* l,int nL,int* r,int nR,int * a){
    //merging the arrays
    int i=0,j=0,k=0;
    while(i<nL && j<nR){
        if(l[i]<=r[j]){
            i++;
            a[k]=l[i];
        }

        else{
            j++;
            a[k]=r[j];
        }
        k++;
    }
    //now elements that are left out
    while(i<nL){
        a[k]=l[i];
        k++;
        i++;
    }
    while(j<nR){
        a[k]=r[j];
        j++;
        k++;
    }
}

这是我实现合并排序算法的mergeSort函数。

void mergeSort(int* a,int n){
    //base case
    if(n<2)
        return;
    //rec case
    int mid=n/2;
    //take 2 arrays of size mid & (n-mid)
    int nL=mid;
    int nR=n-mid;
    int l[nL];
    int r[nR];
    //fill the arrays
    for(int i=0;i<mid;i++){
        l[i]=a[i];
    }
    for(int i=mid;i<n;i++){
        r[i-mid]=a[i];
    }
    //call merge sort recursively
    mergeSort(l,nL);
    mergeSort(r,nR);
    merge(l,nL,r,nR,a);
}

这是我将数组作为输入并传递给函数 mergeSort

的主要函数
int main(){
    int a[100];
    cout<<"Enter no of elements"<<endl;
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    mergeSort(a,n);
    cout<<"After sorting with merge sort"<<endl;
    for(int i=0;i<n;i++){
        cout<<a[i]<<" ";
    }

    return 0;
}

函数merge()是合并两个数组,mergeSort是分割数组并实现归并排序的函数。

我将此作为输入:

8
2 4 1 6 8 5 3 7

输出:

6 1006565088 2096014825 6 2098806136 2096014825 93 8 

【问题讨论】:

  • 我不认为它会改变任何东西。你能告诉我为什么你建议我这样做吗?如果我将 a 作为指针,有什么问题。最终,我得到了基地址。
  • i++; a[k]=l[i]; 这是错误的。其他数组也一样。
  • 为什么能解释一下?
  • 您正在使用可变长度数组。 VLA 不是 C++ 的一部分,tgey 是您的编译器提供的扩展,它不保证工作,并且保证在输入数组中等大(几兆字节)时使您的程序崩溃。在 C++ 中我们很少使用 C 风格的数组,std::vector 提供了更好的选择。
  • 当 l 和 r 都只有一个元素时会发生什么?哪些元素被复制到一个?

标签: c++ arrays sorting mergesort


【解决方案1】:

问题是因为 ij 的值在函数合并中分配给左右数组之前递增。 while 循环应该是:

while(i<nL && j<nR){
        if(l[i]<=r[j]){

            a[k]=l[i];
            i++;  //here was the mistake.
        }

        else{

            a[k]=r[j];
            j++;  // here was the mistake
        }
        k++;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 1970-01-01
    相关资源
    最近更新 更多