Example 60: C language implements a selection method to sort 10 integers.
Analysis: The selection and sorting idea is as follows, with 10 elements a[1] a[10], a[1] and a[2] a[10], if a[1] is better than a[2]~a[10 ] Is small, no exchange is performed, that is, no operation is performed.
If more than one of a[2] and a[10] is smaller than a[1], the largest one of them is exchanged with a[1]. At this time, a[1] stores the smallest number among the ten. By analogy, a total of 9 rounds of comparison are performed, and a[1] a[10] have been stored in ascending order.
To make the overall code logic clearer, Kobayashi is divided into four parts here:
The first part of the keyboard input 10 numbers:
for(i=1;i<=10;i++)//依次键盘录入10个数据
{
printf("array[%d]=",i-1);//数组下标从0开始
scanf("%d",&array[i]);
}
The second part outputs the 10 numbers entered by the keyboard:
for(i=1;i<=10;i++)//将键盘录入的10个数原样输出
{
printf("%5d",array[i]);
}
The third part of the sorting logic:
for(i=1;i<=9;i++)
{
min=i;//把第一个数作为最小的
for(j=i+1;j<=10;j++)
{
if(array[min]>array[j])//判断大小,小的为min
{
min=j;
}
}
temp=array[i]; //大小交换
array[i]=array[min];
array[min]=temp;
}
The fourth part of the 10 numbers after sorting:
for(i=1;i<=10;i++)//输出排序后的10个数
{
printf("%5d",array[i]);
}
Source code demo:
#include<stdio.h>//头文件
int main()//主函数
{
int i,j,min,temp,array[11];//定义整型变量和数组
printf("输入数据:\n");//提示语句
for(i=1;i<=10;i++)//依次键盘录入10个数据
{
printf("array[%d]=",i-1);//数组下标从0开始
scanf("%d",&array[i]);
}
printf("\n");//换行
printf("原样输出:\n");//提示语句
for(i=1;i<=10;i++)//将键盘录入的10个数原样输出
{
printf("%5d",array[i]);
}
printf("\n");//换行
for(i=1;i<=9;i++)
{
min=i;//把第一个数作为最小的
for(j=i+1;j<=10;j++)
{
if(array[min]>array[j])//判断大小,小的为min
{
min=j;
}
}
temp=array[i]; //大小交换
array[i]=array[min];
array[min]=temp;
}
printf("排序输出:\n");//提示语句
for(i=1;i<=10;i++)//输出排序后的10个数
{
printf("%5d",array[i]);
}
printf("\n");//换行
return 0;//主函数返回值为0
}
The compilation and running results are as follows:
输入数据:
array[0]=1
array[1]=4
array[2]=7
array[3]=9
array[4]=4
array[5]=3
array[6]=7
array[7]=9
array[8]=5
array[9]=3
原样输出:
1 4 7 9 4 3 7 9 5 3
排序输出:
1 3 3 4 4 5 7 7 9 9
--------------------------------
Process exited after 8.036 seconds with return value 0
请按任意键继续. . .
I want to see quick sorting, merge sorting and sort likes and tell me
C language selection method to sort 10 numbers
More cases can go to the public account : C language entry to proficient