Selection sort
|

Understanding Selection sort program

Selection Sort is one of the Simplest sorting algorithm out there.

Algorithm

1-First Find the minimum element from the array .

2-Swap it with the First element of the unsorted array.

3-Repeat until whole array is sorted.

Code

#include<stdio.h>
//select min from array 
//reduce the array
int size=5;
int arr[]={456,2,4679,58,5};
int indexx(int a[],int i){
    int min,min_index;
    min=a[i];
    for(int j=i;j<size;j++){
        if(min>a[j]){
            min=a[j];
            min_index=j;
        }
    }
    return min_index;
}
void selectionsort(int a[]){
    int i,k,tmp;
    for(i=0;i<size;i++){
        k=indexx(a,i); //index function returns the index of minimum number
        tmp=a[i];
        a[i]=a[k];
        a[k]=tmp;
    }
    for(i=0;i<size;i++){
        printf("%d \n",a[i]);
    }
}
int main()
{   
    
    selectionsort(arr);
    return 0;
}

Output

Analysis

Time ComplexityO(n^2) for all cases
InplaceYes
StableNo

Similar Posts

Leave a Reply

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