gpt4 book ai didi

c - 数组排序的逻辑错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:03 27 4
gpt4 key购买 nike

问题-
以这样的方式对数组进行排序,即大于第一个元素的数字在右侧,小于第一个元素的数字在左侧
示例输入-
5
4 5 3 7 2 (以4为引用)
示例输出
3 2 4 5 7
我的代码是这样排序的
输入
5
12
16
2
3
56
输出
2
3
2
3
56

int main()
{

int i,j,n,temp;
printf("enter no of elements of array");
scanf("%d",&n);
int a[n];
printf("enter array\n");
for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
j=0;
for(i=1;i<=n-1;i++)
{
if(a[i]<a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=a[j];
j++;
}
}
for(i=0;i<n;i++)
{
printf("Array is%d\n",a[i]);
}
}

最佳答案

首先,

 temp=a[j];
a[j]=a[i];
a[i]=a[j];

应该是

 temp=a[j];
a[j]=a[i];
a[i]=temp;

这解释了重复项。但是一旦你对它进行排序(哈哈),你会发现它不太正确,因为你只将每个数字与其相邻数字进行比较 - 如果数组中的最后一个数字是最小的怎么办? - 你只会将它移到更早的位置(例如,5 个数字列表中的第 4 个位置)。

关于c - 数组排序的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26777393/

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