一、参考代码
- #includestdio.h>
- #include stdlib.h>
- /****************************************
- **选择排序法对十个整数进行排序 ***
- ****************************************/
- //n为数组长度;
- void sort(int a[],int n)
- {
- int temp,min;
- int i=0;
- for(;in;i++)
- {
- min=i; //先假设最小下标为i
- int j=i+1;
- for(;jn;j++)
- if(a[j]a[min])
- min=j; //对i之后的数进行扫描将最小的数赋予min
- if(min!=i)
- {
- temp=a[i];
- a[i]=a[min];
- a[min]=temp;
- } //判断min与i是否相等,若=则说明原假设正确反之交换数值
- printf("No.%d,i=%d,min=%d\t",i+1,i,min);
- int k = 0;
- for(;k10;k++)
- {
- if(k==i)
- printf(" [%d], ",a[k]);
- else
- printf(" %d, ",a[k]);
- }
- printf("\n");
- }
- }
- //用main函数验证
- int main()
- {
- system("clear");
- int a[10]={85,66,34,86,52,74,61,25,24,11};
- int i=0;
- printf("provide you with ten numbers:\n");
- for(;i10;i++)
- printf("%d,",a[i]);
- printf("\n");
- printf("________________________________________________________________\n");
- sort(a,10);
- printf("After selection sort:\n");
- printf("________________________________________________________________\n");
- for(i=0;i10;i++)
- printf("%d,",a[i]);
- printf("\n");
- return 0;
- }
二、运行效果
- provide you with ten numbers:
- 85,66,34,86,52,74,61,25,24,11,
- ________________________________________________________________
- No.1,i=0,min=9 [11], 66, 34, 86, 52, 74, 61, 25, 24, 85,
- No.2,i=1,min=8 11, [24], 34, 86, 52, 74, 61, 25, 66, 85,
- No.3,i=2,min=7 11, 24, [25], 86, 52, 74, 61, 34, 66, 85,
- No.4,i=3,min=7 11, 24, 25, [34], 52, 74, 61, 86, 66, 85,
- No.5,i=4,min=4 11, 24, 25, 34, [52], 74, 61, 86, 66, 85,
- No.6,i=5,min=6 11, 24, 25, 34, 52, [61], 74, 86, 66, 85,
- No.7,i=6,min=8 11, 24, 25, 34, 52, 61, [66], 86, 74, 85,
- No.8,i=7,min=8 11, 24, 25, 34, 52, 61, 66, [74], 86, 85,
- No.9,i=8,min=9 11, 24, 25, 34, 52, 61, 66, 74, [85], 86,
- No.10,i=9,min=9 11, 24, 25, 34, 52, 61, 66, 74, 85, [86],
- After selection sort:
- ________________________________________________________________
- 11,24,25,34,52,61,66,74,85,86,
- [root@localhost select_sort]#
三、一点分析
选择法排序原理:一次选定数组中的每一个数,记下当前位置并假设它是从当前位置开始后面数中的最小数min=i,从这个数的下一个数开始扫描直到最后一个数,并记录下最小数的位置min,扫描结束后如果min不等于i,说明假设错误,则交换min与i位置上数