Selection Sort

Selection sort is an in-place(no need of extra space) sorting algorithm. Selection sort generally use when data(file) size is small. when data or list or file are large then it is inefficient.It is used for sorting the files which have very large values and small keys. This is because selection is made based on keys and swaps are made only when required.
In Selection Sorting ,we are repeatedly find the smallest element ,So it is called Selection Sort.

Explanation of Bubble Sort By Example

Above figure is explaining complete working strategy of Selection Sort.

Animation of Selection Sort

Source From Wikipedia

Flow Chart of Selection Sort

Code Implementation

#include <stdio.h>
int main()
{
    int A[]={0,5,2,1,6,9,7,4};
    int n=sizeof(A)/sizeof(A[0]);
    int minIndex;
    //Start the Selection Sort Logic
    for(int i=0;i<n ;i++) 
    {
        minIndex=i;    // Suppose i index element is smaller
        for(int j=i+1;j<n;j++)
        {
           if(A[minIndex]>A[j])
           {
               minIndex=j;
           }
        }
        // swap the elements
        int temp=A[minIndex];
        A[minIndex]=A[i];
        A[i]=temp;
    }
    //End the Selection Sort Logic
    for(int i=0;i<n;i++)
    {
        printf("%d\n",A[i]);
    }
    return 0;
}

Here in the code,first we set minIndex index element is smaller ,the we search from i+1 to n-1 elements to check whether there is any element which is smaller than index i element,if yes then set index of smaller element to minIndex. and then perform swapping, and repeat this process till n-1.

Time & Space Complexity

Worst case complexity : O(n^{2})
Best case complexity : O(n^{2})
Average Case complexity : O(n^{2}).
Space Complexity : O(1)

Note

Its implementation is very easy.
It is an in-place type algorithm(No need of extra space ).
complexity O(n^{2}) is not a good rate of growth.

Leave a Reply

Your email address will not be published. Required fields are marked *