练习02-23-01 将十个整数进行排序
输入格式:
a[0] = 6
a[1] = 8
a[2] = 9
a[3] = 3
a[4] = 9
a[5] = -7
a[6] = 5
a[7] = 0
a[8] = -4
a[9] = 46
输出格式:
The original numbers are:
6 8 9 3 9 -7 5 0 -4 46
The numbers after the order are:
-7 -4 0 3 5 6 8 9 9 46
--------------------------------
Process exited after 18.05 seconds with return value 0
请按任意键继续. . .
方法1:选择排序,代码如下:
//用选择法对十个整数排序
#include<stdio.h>
int main()
{
int i,j,min,temp,a[10];
for(i=0;i<10;++i){ //用数组来记录初始化的十个数
printf("a[%d] = ",i);
scanf("%d",&a[i]);
putchar('\n');
}
printf("The original numbers are:\n");
for(i=0;i<10;++i){
printf("%5d",a[i]);
}
printf("\n");
for(i=0;i<9;++i){
//min=i;
for(j=i+1;j<10;++j){
if(a[i]>a[j]){
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
printf("The numbers after the order are:\n");
for(i=0;i<10;++i){
printf("%5d",a[i]);
}
return 0;
}
方法2:冒泡排序,代码如下:
//冒泡排序
#include<stdio.h>
int main()
{
int a[10],i,j,temp;
for(i=0;i<10;++i){
printf("a[%d] = ",i);
scanf("%d",&a[i]);
putchar('\n');
}
printf("The original numbers are: ");
for(i=0;i<10;++i){
printf("%5d",a[i]);
}
putchar('\n');
for(i=0;i<9;++i){ //外侧循环的目的,让里面的数从头开始
for(j=0;j<10-i;++j){
if(a[j]>a[j+1]){
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
printf("The scorted numbers are: ");
putchar(' ');
for(i=0;i<10;++i){
printf("%5d",a[i]);
}
return 0;
}
结果
a[0] = 6
a[1] = 8
a[2] = 9
a[3] = 3
a[4] = 9
a[5] = -7
a[6] = 5
a[7] = 0
a[8] = -4
a[9] = 46
The original numbers are: 6 8 9 3 9 -7 5 0 -4 46
The scorted numbers are: -7 -4 0 3 5 6 8 9 9 46
--------------------------------
Process exited after 19.1 seconds with return value 0
请按任意键继续. . .