Tuesday 28 June 2016

Sorting program #2 : Selection Sort

Selection sort 

is also very easy and time taking fundamental algorithm of  sorting .
The logic behind this is simple . Like , we need to select the smallest element and assign that value to the appropriate index .
It follows the following algorithm :

* Selection sort :

Given a vector K with N elements :
 o) PASS : pass number position of the first element of vector to be examined in pass
 o) iMin : index of the smallest number
 o) I :    idices !



Step 1 : [Loop on pass index]
    Repeat thru step 4 for PASS = 1,2,3,...,N-1
   
Step 2 : [Initialize minimum index]
    iMin = PASS
   
Step 3 : [Make a pass and obtain element with smallest value]
    Repeat for I = PASS+1,PASS+2,...,N
    If K[I] < K[iMin]
    Then iMin = I
   
Step 4 : [Exchange elements]
    If iMin =/= PASS
    Then K[PASS] <-> K[iMin]
   
Step 5 : [Finished]


Try to write a code for it , else copy the code given below and check !


C Program : Selection Sort 



//selection sort
#include < stdio.h >
void main()
{
    int i,iMin,j,k,temp,n;// declaring required variables 
    printf("Enter number of elements :");
    scanf("%d",&n);
    int array[n];
    printf("Enter the elements :\n");
    for(i=0;i < n;i++)//getting input from user as usual
    {
        printf("Element %d : ",i+1);
        scanf("%d",&array[i]);
    }
    /* Selection sort */
    for(i=0;i < n-1;i++)// outer loop : lets call it a pass
    {
        iMin = i;/* Changing index for minimum of the array elements */
        for(j=i+1;j < n;j++)/*for j < i+1 , all indices are sorted with the appropriate value*/
        {
            if(array[j] < array[iMin])/* choosing the minimum */
            {
                iMin = j;
            }
        }
        temp = array[i];
        array[i] = array[iMin];/*Swapping of minimum value to appropriate index*/
        array[iMin] = temp;
    }
    printf("Here is the sorted array !\n");// printing result 
    for(i=0;i < n;i++)
    {
        printf("%d ",array[i]);
    }

}



For addition details :
You can always see what computer is doing .
For ex. add another loop printing the array after every pass , like this ->


Keep in mind , there is a chance of silly mistake 
### Don't use iterator " i " for printing intermediate results , this disturbs the value of i and cause an Error .

After printing intermediates we can clearly see that , each time the lowest one is replaced to an appropriate index !
































I hope you enjoyed reading this !
Any suggestions and comments are always accepted .


Thank you !

No comments :

Post a Comment