我正在运行合并排序实现,它在https://code.hackerearth.com/4a1c9cn中提供了正确的结果,但https://www.tutorialspoint.com/compile_c_online.php中的结果错误。
有人可以告诉我错误和要记住的事情,以避免将来出现这样的错误。 样本测试案例:5 3 7 5 9 2 第二个编译器的错误答案:03579 代码:
#include <stdio.h>
#include <stdlib.h>
void merge(int A[], int left[], int right[], int n)
{
int i=0, j=0, k=0, m = n/2, d = n-m;
while(i<m && j<d)
{
if(left[i] <= right[j]) A[k++] = left[i++];
else A[k++] = right[j++];
}
if(i == m)
for(;k<n; k++, j++) A[k] = right[j];
else if(j == d)
for(; k<n; k++, i++) A[k] = left[i];
return;
}
void MergeSort(int A[], int n)
{
if(n==1) return;
int m = n/2;
int* left = (int*)malloc(m*sizeof(int));
int* right = (int*)malloc((n-m)*sizeof(int));
int i, j;
for(i=0; i<m; i++) left[i] = A[i];
for(i=m; i<n; i++, j++) right[j] = A[i];
MergeSort(left, m);
MergeSort(right, (n-m));
merge(A, left, right, n);
return;
}
int PrintArr(int A[], int n);
void getArr (int A[], int n);
int main(int argc, char** argv)
{
int n, *arr;
scanf("%d", &n);
arr = (int*)malloc(n*sizeof(int));
getArr(arr, n);
MergeSort(arr, n);
PrintArr(arr, n);
return 0;
}
答案 0 :(得分:0)
在有用的评论之后,我能够修复代码。错误的原因是内存泄漏。修改后的代码:
#include <stdio.h>
#include <stdlib.h>
void merge(int A[], int l, int h)
{ int* temp = (int*)malloc((h-l+1)*sizeof(int));
int i=l, k=0, m = l + (h-l)/2, j = m+1;
while(i<=m && j<=h)
{
if(A[i] <= A[j]) temp[k++] = A[i++];
else temp[k++] = A[j++];
}
if(i > m)
for(;k<=h; k++, j++) temp[k] = A[j];
else if(j > h)
for(; k<=h; k++, i++) temp[k] = A[i];
for(i=l, k=0; i<=h; i++,k++) A[i] = temp[k];
return;
}
void MergeSort(int A[], int l, int h)
{
if(h-l<1) return;
int m = l + (h-l)/2;
MergeSort(A, l, m);
MergeSort(A, m+1, h);
merge(A, l, h);
return;
}
int PrintArr(int A[], int n)
void getArr (int A[], int n)
int main(int argc, char** argv)
{
int n, *arr;
scanf("%d", &n);
arr = (int*)malloc(n*sizeof(int));
getArr(arr, n);
MergeSort(arr, 0, n-1);
PrintArr(arr, n);
return 0;
}