gpt4 book ai didi

c++ - 归并排序程序陷入错误

转载 作者:行者123 更新时间:2023-11-30 21:30:17 24 4
gpt4 key购买 nike

请帮我猜测理解以下代码中的错误。它返回相同的数组。

例如,如果我将 2, 5, 3, 1 作为输入,它会返回 2, 5, 3, 1,而不进行排序。

示例输出:

Enter the total number of elements: 4
Enter the elements which to be sort:
2
5
3
1
Un-Sorted Array: 2531
Sorted Array: 2531

这是我的代码 - 出了什么问题?

#include <iostream>
using namespace std;
int l,m,h;

int merge(int A[], int low, int mid, int high){

int A1[10];
int A2[10];
int n1, n2, i, j, k;

n1=m-l+1;
n2=h-m;

for (i=0; i<n1; i++)
A1[i]=A[l+i];

for (j=0; j<n2; j++)
A1[j]=A[m+j+1];


A1[i]=9999;
A2[i]=9999;

i=0;
j=0;
for(k=1; k<=h; k++){
if (A1[i] <= A2[j])
A[k]=A1[i++];
else
A[k]=A2[j++];
}
return 0;

}

int merge_sort(int A[],int low,int high){

int mid;

if(low<high){
mid=(low+high)/2;
merge_sort(A,low,mid);
merge_sort(A,mid+1,high);
merge(A,low,mid,high);
}
return 0;
}

int A[20];

int main(){

int i,n;

cout << "Enter the total number of elements: ";
cin >> n;

cout << "\nEnter the elements which to be sort: ";

for(i=0;i<n;i++){
cin >> A[i];
}

cout << " \nUn-Sorted Array: ";

for(i=0;i<n;i++){
cout << A[i];
}

merge_sort(A,0,n-1);

cout << "\nSorted Array: ";

for(i=0;i<n;i++){
cout << A[i];

}
return 0;
}

最佳答案

int merge(int A[], int low, int mid, int high){

int A1[10];
int A2[10];
int n1, n2, i, j, k;

n1=mid-low+1;//use parameter
n2=high-mid;//ditto

for (i=0; i<n1; i++)
A1[i]=A[low+i];//ditto

for (j=0; j<n2; j++)
A2[j]=A[mid+j+1];//ditto


A1[i]=9999;
A2[j]=9999;//typo i -> j

i=0;
j=0;
for(k=low; k<=high; k++){//k=1 typo and use parameter
if (A1[i] <= A2[j])
A[k]=A1[i++];
else
A[k]=A2[j++];
}
return 0;

}

关于c++ - 归并排序程序陷入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26903341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com