- Choose the basic idea of sorting :
Scan n Records, select the smallest record to output it, then scan the remaining N-1 records, select the smallest record to output, ... Repeat the process until the last record is left.
1 //1. Simple selection of sorting2 voidSelectsort (intA[],intnum)3 {4 intmin=0, temp=0;//record the minimum number of the corresponding subscript5 for(intI=0; i<num-1; i++)6 {7min=i;8 for(intj=i+1; j<num;j++)9 {Ten if(a[min]>A[j]) One { Amin=J; - } - } the if(min!=i) - { -temp=A[i]; -a[i]=A[min]; +a[min]=temp; - } + } A } at - - intMain () - { - intarray[9]={0}; - Srand (Time (NULL)); in for(intI=0;i<9; i++) - { toArray[i]=rand ()% -;//generate 0-99 of random numbers + } -cout<<"array prior to sorting \ n"; thePrint (Array,9); *Selectsort (Array,9); $cout<<"array after sorting \ n";Panax NotoginsengPrint (Array,9); - theSystem"Pause"); + return 0; A}
Operation Result:
2. Calculation of time complexity
The first trip requires a n-i comparison, so the number of comparisons is n (n-1)/2. Exchange times, preferably exchange 0 times, the worst exchange times is n-1 times. The final sort count is the sum of the comparisons and the number of exchanges. As a result, the final total time complexity is still not (N2).
Sort 1-Simple selection sort