gpt4 book ai didi

c - 使用C进行归并排序,输出出错

转载 作者:行者123 更新时间:2023-11-30 14:42:58 25 4
gpt4 key购买 nike

我在CodeBlocks 17.0.1中编写了代码
看起来它只是对数组中的某些元素进行排序,而不是全部。另外,我找不到我的代码和我拥有的示例之间的差异,并且仍然不知道出了什么问题。感谢您的帮助!

#include <stdio.h>
#include <stdlib.h>


void merge(float x[], float y[], int l, int m, int r)
{
int ptr_1,ptr_2,ptr_y;
ptr_1 = ptr_y = l;
ptr_2 = m+1;
while((ptr_1<=m) && (ptr_2<=r))
{
if(x[ptr_1] <= x[ptr_2])
y[ptr_y++] = x[ptr_1++];
else
{
y[ptr_y++] = x[ptr_2++];
}
}
while(ptr_1<=m)
y[ptr_y++] = x[ptr_1++];
while(ptr_2<=r)
y[ptr_y++] = x[ptr_2++];

}

void merge_sort(float a[],float b[],int l, int r)
{
if(l < r)
{ int m = l + (r-l)/2;
merge_sort(a,b,l,m);
merge_sort(a,b,m+1,r);
merge(a,b,l,m,r);
}

}

int main()
{
float a[3] ={10.3,8.5,3.23},b[3];
int i,j;
float *temp = b;
merge_sort(a,temp,0,2);
for(i=0;i<3;i++)
{
printf("%.2f ",b[i]);
}
printf("\n");
system("pause");
return 0;
}

输出:3.23 10.30 8.50

最佳答案

这是工作代码:

#include <stdio.h>
#include <stdlib.h>


void merge(float a[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */
float L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = a[l + i];
for (j = 0; j < n2; j++)
R[j] = a[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
a[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
a[k] = R[j];
j++;
k++;
}
}

void merge_sort(float a[],int l, int r)
{
if(l < r)
{ int m = l + (r-l)/2;
merge_sort(a,l,m);
merge_sort(a,m+1,r);
merge(a,l,m,r);
}

}

int main()
{
float a[3] ={10.3,8.5,3.23};
int i,j;
merge_sort(a,0,2);
for(i=0;i<3;i++)
{
printf("%.2f ",a[i]);
}
printf("\n");
system("pause");
return 0;
}

still don't know what goes wrong

为什么使用两个不同的数组?只需一个数组就足够了,但它包含两个逻辑数组,索引 l 和 m 引用每个数组的开头。

关于c - 使用C进行归并排序,输出出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54239528/

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