gpt4 book ai didi

c - 以所需的方式对数组进行排序

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

我需要将奇数位置的元素按降序排序,将偶数位置的元素按升序排序。这是我的代码,我无法打破第一个循环。

#include<stdio.h>

int main()
{
int n, t;

printf("Enter the size of the array\n");
scanf("%d", &n);
int i, a[n];

if ((n > 20) || (n <= 0))
printf("Invalid Size");
else
{
printf("Enter the values\n");
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}

for (i = 0; i < n; i + 2)
{
if (a[i] > a[i + 2])
{
t = a[i];
a[i] = a[i + 2];
a[i + 2] = t;
}
}
for (i = 1; i < n; i + 2)
{
if (a[i] < a[i + 2])
{
t = a[i];
a[i] = a[i + 2];
a[i + 2] = t;
}
}
for (i = 0; i < n; i++)
{
printf("%d\n", a[i]);
}
}
}

最佳答案

对于根据 C 标准的初学者,不带参数的函数 main 应声明为

int main( void )

将变量 n 声明为类型 int 并随后检查其值是否小于零没有多大意义。最好将其声明为 size_t 类型。

数组应该在检查后声明

if ((n > 20) || (n <= 0))
printf("Invalid Size");
else
{
int a[n];
//...

像这样的循环

for (i = 0; i < n; i + 2)

变量i没有增加。很明显你的意思是i += 2

循环仅将第一个最小偶数和第一个最大奇数元素移动到数组的末尾。您需要额外的循环来对数组的其他元素执行相同的操作。那就是冒泡排序算法的实现是不正确的。

这是一个演示程序,展示了如何根据数组偶数和奇数元素的要求对数组进行排序。

#include <stdio.h>

#define N 20

int main(void)
{
int a[N] = { 18, 1, 16, 3, 14, 5, 12, 7, 10, 9, 8, 11, 6, 13, 4, 15, 2, 17, 0, 19 };

for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );

for ( size_t n = N, last; !( n < 3 ); n = last )
{
for ( size_t i = last = 2; i < n; i++ )
{
if ( ( i % 2 == 0 && a[i] < a[i - 2] ) ||
( i % 2 == 1 && a[i - 2] < a[i] ) )
{
int tmp = a[i];
a[i] = a[i - 2];
a[i - 2] = tmp;
last = i;
}
}
}

for ( size_t i = 0; i < N; i++ )
{
printf( "%d ", a[i] );
}
putchar( '\n' );

return 0;
}

程序输出为

18 1 16 3 14 5 12 7 10 9 8 11 6 13 4 15 2 17 0 19 
0 19 2 17 4 15 6 13 8 11 10 9 12 7 14 5 16 3 18 1

关于c - 以所需的方式对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44784114/

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