The basic idea
Default unsorted first region a minimum first element, and then pick the smallest element in the element from the rear, with the switching element, until the cycle is complete.
Algorithm code
1 // simple selection sort 2 void SelectSort ( int * ARR, int n-) . 3 { . 4 int I, J; . 5 int TEMP; . 6 int minIndex; . 7 for (I = 0 ; I <n-- 1 ; I ++) / / do i-times sorted, total n-1 times, since the n-th Run only a constant is the largest . 8 { . 9 minIndex = i; 10 for (J = i + . 1 ; J <n; J ++ ) . 11 { 12 is IF (arr [j] <arr [minIndex]) 13 minIndex = j; 14 } 15 if (minIndex! = I) // 后面有更小的元素 16 { 17 temp = arr [i]; 18 arr [i] = arr [minIndex]; 19 arr [minIndex] = temp; 20 } 21 } 22 }
Analysis of Algorithms
I from the selected record in the minimum recording requires a relatively i -1 times.
Of I (I = 0 ~ n-2-) selected from ni times the minimum recording record requires a relatively ni-1.
N records for simple selection sort are necessary for the number of comparisons keyword amount to:
Number of movements recorded positive sequence is the minimum value 0, in reverse order of the maximum value of 3 (n-1).
Sort select the best and the worst average time complexity of O (N2) .