//将具有20个数组元素的整型数组的前10个数升序排列,后10个降序排列。
#include
main()
{
int a[20], trans, smlr, bigr;
for (int i = 0; i < 20; i++)
scanf_s("%d", &a[i]);
for (int old = 0; old < 10; old++)
{
smlr = old;
for (int new = 1 + old; new < 10; new++)
if (a[new] < a[old])
smlr = new;
if (smlr != old)
{
trans = a[old];
a[old] = a[smlr];
a[smlr] = trans;
}
}
for (int old = 10; old < 20; old++)
{
bigr = old;
for (int new = 1 + old; new < 20; new++)
if (a[new] > a[old])
bigr = new;
if (bigr != old)
{
trans = a[old];
a[old] = a[bigr];
a[bigr]=trans;
}
}
for (int i = 0; i < 20; i++)
printf("%d ", a[i]);
}
调试结果:
1
2
3
4
5
6
7
8
9
0
12
13
11
15
10
14
16
17
18
19
0 1 2 3 4 5 6 7 8 9 19 18 12 17 11 15 16 14 13 10
D:\Files\vs\test1\x64\Debug\test1.exe (进程 17308)已退出,代码为 0。
按任意键关闭此窗口. . .
if (a[new] < a[old])
应该是if (a[smlr] < a[old])
if (a[new] > a[old])
应该是
if (a[bigr] > a[old])
你的输入数据太整齐了,导致前半部分不需要怎么排就是有序的,你换个数据,前半部分也是乱的
因为你每一次做比较的都是第一个数,故而相当于第一个数和最靠后且比它大的数做交互(并不是最大的)
改动处见注释,供参考:
#include <stdio.h>
int main() //修改 int
{
int a[20], trans, smlr, bigr;
for (int i = 0; i < 20; i++)
scanf_s("%d", &a[i]);
for (int old = 0; old < 10 - 1; old++) //(int old = 0; old < 10; old++)
{
smlr = old;
for (int New = 1 + old; New < 10; New++) //new 改成 New
if (a[New] < a[smlr]) //if (a[New] < a[old])
smlr = New;
if (smlr != old)
{
trans = a[old];
a[old] = a[smlr];
a[smlr] = trans;
}
}
for (int old = 10; old < 20 - 1; old++) //(int old = 10; old < 20; old++)
{
bigr = old;
for (int New = 1 + old; New < 20; New++) //new 改成 New
if (a[New] > a[bigr]) //if (a[New] > a[old])
bigr = New;
if (bigr != old)
{
trans = a[old];
a[old] = a[bigr];
a[bigr] = trans;
}
}
for (int i = 0; i < 20; i++)
printf("%d ", a[i]);
return 0;
}