In this method, the smallest item in a given series of n elements is found and is placed in the first position. Then the smallest item from the remaining (n-l) elements is found and is placed in the second position and so on. This method requires (n-l) passes for arranging n elements.
Example
The program illustrates sorting numbers in ascending order using Selection sort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <iostream.h> const int m = 4; void main() { int data[m],i,j,k,min,minindex,n; cout<< "Enter the number of values " <<endl; cin>>n; cout<< "Enter the values " <<endl; for (i=0;i<n;i++) cin>>data[i] ; cout<<endl; cout<< "The list to be sorted is " <<endl; for (i=0;i<n;i++) cout<<data[i]<< " " ; cout<< "\n" ; cout<< "Selection sort " <<endl; cout<< " ---------------" ; for (i=0;i<n;i++) { minindex=i; min=data[i] ; for (j=i+1;j<n;j++) { if (min>data[j]) { minindex=j; min=data[j] ; } } data [minindex] =data [i]; data[i]=min; cout<<endl<< "pass " <<i+1; for (k=0;k<n;k++ ) cout<< " " <<data[k]; cout<<endl; }} |
In the outer for loop, the variables min and minindex are initialized to i and data[i].In the first pass the minimum of all the elements, min is found. Index corresponding to minimum value is stored in minindex. Values corresponding to minindex and i are swapped, where i denotes the pass.
Input and Output:
Enter the number of values 5
Enter the values
67 22 58 49 10
The list to be sorted is
67 22 58 49 10
Selection sort
pass 1 10 22 58 49 67
pass 2 10 22 58 49 67
pass 3 10 22 49 58 67
pass 4 10 22 49 58 67
pass 5 10 22 49 58 67