深入解析:【C语言代码】数组排序
2025-09-24 11:24 tlnshuju 阅读(15) 评论(0) 收藏 举报【题目】
输入一串整型正整数,设计脚本,给输入的数组进行递增排序。输入一系列数据直到回车键结束,总长度不超过100.
【解题思路】
注意:
1.当输入元素个数为未知数时我们应该如何应对?
用while(1)无限循环应对,输入的数组下标值在while循环中自加,输入回车结束则利用if语句判断字符是否为换行符‘\n’,是则break结束循环。
2.常见的数组排序方法有哪些?
排序数组为算法基础,需熟练各个排序的代码。
各个排序算法总结,在另一篇文章有专门记录。
本题用的是选择排序,直接背模板吧。
直接上代码!
【Code】
#include
void selectionSort(int a[],int n)
{
int i,j,min_Index,temp;
//外层循环执行n-1次
for(i = 0;i < n-1;i ++)
{
//内层循环的每一次操作都是找到待排序数组的最小值和第i个元素交换
min_Index = i;
for(j = i+1;j < n;j ++)
{
if(a[j] < a[min_Index])
{
min_Index = j;
}
}
temp = a[i];
a[i] = a[min_Index];
a[min_Index] = temp;
}
}
int main()
{
int a[101];
int i;
int n = 0;
char c;
//格式化控制输入,遇到回车结束输入
while(1)
{
scanf("%d%c",&a[n],&c);
n ++;
if(c == '\n') break;
}
//调用排序函数
selectionSort(a,n);
//输出排序后的数组
for(i = 0;i < n;i ++)
{
printf("%d ",a[i]);
}
}
【Input Example】
3 2 10 5
【Output Result】

浙公网安备 33010602011771号