[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
试题描述:
用选择法对10个整数从小到大排序。请使用数组实现。
输入
输入10个整数,相邻两项之间用一个空格隔开。
输出
输出从小到大排序后的整数,相邻两项之间用一个空格隔开。
输入示例
46 73 62 11 5 3 52 32 98 23
输出示例
3 5 11 23 32 46 52 62 73 98
数据范围
输入输出均为int范围的整数
先来看一张图来回顾一下什么是选择排序(图片来自网络)
我们先来实现最基础的部分
#include <stdio.h> #include <stdlib.h> int main() { int a[10],i,j,q,m;
scanf("%d %d %d %d %d %d %d %d %d
%d",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5],&a[6],&a[7],&a[8],&a[9]);
即输入数组,由于我打这段代码的时候旁边有人在外放DYKS所以情绪有些暴躁所以选择了简单粗暴的方法,可根据个人习惯修改
之后是排序部分:从图不难看出,该排序法需要两层迭代,一层是从左往右顺序依次检索,另一层则是从每个起始端再次向右检索,依次来保证左<右,因此:
for(i=0;i<10;i++){ //总迭代循环:按从0开始从左往右顺序依次检索 for(j=i;j<10;j++){
//次迭代循环:变换初始值,来从初始值检索====== int min=a[i]; //这里设最开始的初始值为 局部变量min ↑ 接着循环返回
if(a[j]<a[i]){ //条件:若在之后的检索中发现比初始值小的值 ↑ 再执行一遍 min=a[j]; //先把 较小值赋值给min以防丢失 ↑
直到a[9]为止 a[j]=a[i]; //然后再把初始值赋值给较小值完成替换 ↑ 数组的值被检索 a[i]=min;
//最后把较小值值赋值给初始值================= 完毕 } } }
最后打印该数组:
for(q=0;q<10;q++){ printf("%d",a[q]); printf(" "); } return 0; }
综上,最终代码:
#include <stdio.h> #include <stdlib.h> int main() { int a[10],i,j,q,m;
scanf("%d %d %d %d %d %d %d %d %d
%d",&a[0],&a[1],&a[2],&a[3],&a[4],&a[5],&a[6],&a[7],&a[8],&a[9]);
for(i=0;i<10;i++){ for(j=i;j<10;j++){ int min=a[i]; if(a[j]<a[i]){ min=a[j];
a[j]=a[i]; a[i]=min; } } } for(q=0;q<10;q++){ printf("%d",a[q]); printf(" "); }
return 0; }
(解法不唯一,仅供参考)