In a group of numbers to be sorted, choose the smallest (or largest) number to exchange with the number in the first position; then find the smallest (or largest) number and the number in the second position among the remaining numbers Exchange, and so on, until the n-1th element (the penultimate number) is compared with the nth element (the last number).
Code
// 比a[i]小的最小元素下标intselect_min(int a[],int n,int i){
int j = i;for(int k = i +1; k < n;++k){
if(a[j]> a[k]){
j = k;}}return j;}voidselect_sort(int a[],int n){
for(int i =0; i < n;++i){
int min =select_min(a, n, i);if(i != min){
int temp = a[i];
a[i]= a[min];
a[min]= temp;}// 测试用print(a, n, i +1);}}
test
Code
#include<iostream>usingnamespace std;voidprint(int a[],int num,int index){
cout <<" index = "<< index <<" : ";for(int i =0; i < num;++i){
cout << a[i]<<" ";}
cout << endl;}intmain(){
int a[]={
7,6,5,4,3,2,1};select_sort(a,sizeof(a)/sizeof(a[0]));
cin.get();return0;}
result
index =1:1654327
index =2:1254367
index =3:1234567
index =4:1234567
index =5:1234567
index =6:1234567
index =7:1234567