#include <stdio.h>
int output[50];
void mergesort (int a[], int low, int high);
void merge ( int a[], int l, int m, int h );
int main(void)
{
int n,a[50],i;
printf("Enter total elements\n");
scanf("%d",&n);
printf("Enter the elements\n");
for ( i = 0; i < n; i++ )
{
scanf("%d",&a[i]);
}
mergesort(a,0,n-1);
printf("The sorted elements are\n");
for ( i = 0; i < n; i++ )
{
printf("%d\n",output[i]);
}
return 0;
}
void mergesort (int a[], int low, int high)
{
int mid;
if ( low < high )
{
mid = (low+high)/2;
mergesort(a,0,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
}
void merge ( int a[], int l, int m, int h )
{
int i = l,j = m+1;
int temp[50],z,t=l;
while ( (i <= m) && (j <= h) )
{
if (a[i] <= a[j])
{
temp[t] = a[i];
t++;
i++;
}
else
{
temp[t] = a[j];
t++;
j++;
}
}
while ( i <= m )
{
temp[t] = a[i];
i++;
t++;
}
while ( j <= h )
{
temp[t] = a[j];
j++;
t++;
}
for ( z = l; z <= h; z++ )
{
output[z] = temp[z];
}
}
我用 C 语言实现了合并排序。但是,它有一些问题。 当我将输入设置为 123456 时,输出结果为 321654。似乎我错过了一些循环。当我输入 54321 时,它显示输出为 21543。问题是什么,我无法理解。请帮忙。
最佳答案
最后一条语句应该是 a[z] = temp[z];
而不是 output[z] = temp[z];
并打印 a
数组。在合并排序中,将使用以前的合并结果,因此如果复制到新数组,则不会完成正确的合并。
关于c - 这个合并排序有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24240178/