Simple selection sorting algorithm
first, the basic idea: every trip loops through the records to be sorted to select the smallest record of the keyword, placed in the order of the final row of the child table, until all the records sorted.
Second, C language code:
1#include <stdio.h>2#include <stdlib.h>3 4 voidSelectsort (RecType r[],intN)5 {6 inti;7 intJ;8 intK;9 RecType tmp;Ten One for(i =0; I < n1; i++) { AK =i; - - //in the current unordered area r[i...n-1], select the r[k with the smallest key] the for(j = i +1; J < N; J + +) { - if(R[j].key <R[k].key) { -K = J;//k the location of the smallest keyword currently found - } + } - + //Exchange R[i] and R[k] A if(k! =i) { atTMP =R[i];i -R[i] =R[k]; -R[K] =tmp; - } - } -}
Three, algorithm analysis
Time complexity: By the algorithm code, the simple selection of the order is composed of two loops, for n sorted records, the outer layer must undergo a n-1 cycle, while the inner layers must go through (n-1-i) cycles, where 0≦i≦n-1, and every comparison, such as the need to exchange record sorting position must be moved record three times before can achieve the goal. So for a simple choice of sort:
The minimum number of times the keyword comparison and record movement is (n-1) (n-i-1), where 0≦i≦n-1, the algorithm's time complexity is O (n²).
The maximum number of keyword comparisons and records moved is (n-1) [3 (N-i-1)], where 0≦i≦n-1, the time complexity of the algorithm is O (n²).
The average comparison of keywords and the number of records moved is (n-1) (n-i-1), where 0≦i≦n-1, the time complexity of the algorithm is O (n²).
Space complexity: The algorithm code shows that the additional space required is only one TMP variable, so the simple choice of sorting algorithm space complexity of O (1).
Iv. thinking
The idea of simple selection sorting algorithm is very simple, but the efficiency is very low, the actual engineering application is very few, how to optimize the algorithm?
Simple selection sorting