The idea of sorting is simple, and it works by selecting the smallest (or largest) element of the data element to be sorted each time, storing it at the beginning of the sequence until all the data elements are sorted out.
The choice of sorting is easier to implement, but less efficient, O (N2).
The C language code is implemented as follows:
1 //Select a sort of C language implementation2 voidSelection_sort (inta[])3 {4 intI, J;5 intMin =0;6 for(i=0; i<maxsize-1; i++)7 {8 for(j=i; j<maxsize; J + +)9 {Ten if(A[j] <=A[min]) { OneMin =J; A } - } - swap (A, I, min); the } -}
A simple test case:
#include <stdio.h>#defineMAXSIZE 10voidSelection_sort (inta[]);voidSwapintA[],intIintj);//Select a sort of C language implementationvoidSelection_sort (inta[]) { intI, J; intMin =0; for(i=0; i<maxsize-1; i++) { for(j=i; j<maxsize; J + +) { if(A[j] <=A[min]) {min=J; }} swap (A, I, min); }}voidSwapintA[],intIintj) { inttemp =A[i]; A[i]=A[j]; A[J]=temp;}intMain () {intA[maxsize]; inti; printf ("Please input the num:\n"); for(i=0; i<maxsize; i++) {scanf ("%d",&A[i]); } printf ("before the sort:\n"); for(i=0; i<maxsize; i++) {printf ("%d", A[i]); } printf ("\ n"); Selection_sort (a); printf ("After the sort:\n"); for(i=0; i<maxsize; i++) {printf ("%d", A[i]); } printf ("\ n");}View Code
Selection sort of basic algorithm