当前位置:网站首页>C语言入门实战(14):选择排序
C语言入门实战(14):选择排序
2022-08-03 05:57:00 【liberg】
这是《C语言入门实战》系列的第14篇。
上一篇:C语言入门实战(13):十进制数转二进制
题目
对输入的任意n个(n<=50)1000以内的正整数按升序排序,然后输出,n由用户在程序运行时输入,请编程实现。
要求
每个整数输出时占4个位置,输出格式请采用%4d
。
输入输出格式示例:
输入:6<回车>
10 30 90 20 10 80<回车>
输出: 10 10 20 30 80 90
参考代码
#include <stdio.h>
#include <stdlib.h>
// 对数组a中前n个元素
// 进行选择排序
void sort(int a[], int n) {
int i,j;
//每一轮将当前轮(下标范围[i,n-1])最小的元素交换到最前面
for(i=0;i<n-1;i++) {
for(j=i+1;j<n;j++) {
if(a[i]>a[j]) {
//交换a[i]和a[j]
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
int main(int argc, char *argv[]) {
int n;
int a[50];
scanf("%d", &n);
int i;
for(i=0;i<n;i++) {
scanf("%d", &a[i]);
}
sort(a, n);
for(i=0;i<n;i++) {
printf("%4d", a[i]);
}
return 0;
}
代码复盘
- 数组可以定义为
int a[50];
,然后根据输入的个数n(n<50)
,把n个数据存放在数组的前n个元素中,再对a[0]~a[n-1]
进行排序。 - 定义了一个排序函数
void sort(int a[], int n) {}
,内部通过选择排序算法对数组a中的前n个元素进行从小到大排序。
边栏推荐
- MySQL之concat的用法
- Chrome 配置samesite=none方式
- 信息学奥赛一本通T1454:山峰和山谷
- 连续型特征做embedding代码示例
- El - tree to set focus on selected highlight highlighting, the selected node deepen background and change the font color, etc
- 信息学奥赛一本通T1450:Knight Moves
- 【卫朋】硬件创业:营销与开发同行
- ES6中 async 函数、await表达式 的基本用法
- nvm 卸载详细流程
- pyspark @udf 循环使用变量问题
猜你喜欢
随机推荐
cnpm的安装与使用
El - tree set using setCheckedNodessetCheckedKeys default check nodes, and a new check through setChecked specified node
Embedding的两种实现方式torch代码
npx 有什么作用跟意义?为什么要有 npx?什么场景使用?
信息学奥赛一本通T1449:魔板
sql中 exists的用法
volatile
Detailed explanation and reproduction of AlexNet network
信息学奥赛一本通T1448:深搜的剪枝技巧 电路维修
【Shell】3万字图文讲解带你快速掌握shell脚本编程
empty() received an invalid combination of arguments - got (tuple, dtype=NoneType, device=NoneType),
关于利用canvas画带箭头的直线旋转
CISP-PTE真题演示
pyspark --- count the mode of multiple columns and return it at once
unity 摄像机旋转拖拽缩放场景
5G网络入门基础--5G网络的架构与基本原理
用代码构建UI界面
MYSQL存储过程注释详解
DIFM网络详解及复现
MySQL - 触发器