At the beginning of the selection sort, we scan the entire list, find its smallest element, and then swap with the first element, placing the smallest element in its final position in the ordered table. We then start by scanning the list from the second element, finding the smallest element in the last n-1 element, swapping the position with the second element, and placing the second smallest element in its final position. In general, when I scan the list for the first time (the value of I from 0 to n-2), the algorithm in the last N-i elements to find the smallest element, and then take it and the AI Exchange. After the n-1, the list is sorted out.
Algorithm pseudo-code (assuming the list is implemented by an array)
Selectionsort (a[0... n-1])// Input: A sortable array a[0...n-1]// Output: Array in ascending order A[0...n-1] for i←0 to n2do min←i for j←i+1 to n1do if a[j]<a[min] min←j Swap a[i] and a[min]
Number of executions
For any input, the selection sort is an θ (N2) algorithm. Note, however, that the key is swapped only for θ (n), or more precisely, n-1 times (I loop performs the interchange once for each repetition). This feature makes selection sorting preferable to other sorting algorithms.
C + + code
#include <iostream>using namespacestd;voidSelectionsort (intA[],intN) { for(inti =0; I < n1; i++) { intMin =i; for(intj = i +1; J < N; J + +) { if(A[j] <a[min]) min=J; } swap (A[i], a[min]); }}intMain () {intA[] = { the, $, the, -, in, the, -}; Selectionsort (A,sizeof(a)/sizeof(a[0])); for(inti =0; I <sizeof(a)/sizeof(a[0]); i++) {cout<< A[i] <<" "; } cout<<Endl; return 0;}
The choice of 3.1.1 Brute force method