C program to sort using selection sort

This program demonstrates selection sort in C. The time complexity of selection sort is O(n2). The advantage of selection sort is its simplicity and the disadvantage is that it is more time consuming when sorting large arrays. Selection sort finds smallest element in a list and replaces it with the left most element. This procedure will be repeated till the whole list is sorted.

Program


//Implementation of selection sort program in c

#include<stdio.h>

#include<conio.h>

void main()

{

int a[25],i,j,n,small,t;

printf("Enter the size of the array\n");

scanf("%d",&n);

printf("Enter the elements\n");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

for(i=0;i<n;i++)                   //Selection sort starts here.

{

    small=a[i];

    for(j=i+1;j<n;j++)

    {

        if(a[j]<small)

        {

            small=a[j];

            t=a[i];

            a[i]=small;

            a[j]=t;

        }

    }

}

printf("Array after selection sort\n");

for(i=0;i<n;i++)

{

printf("%d ",a[i]);

}

getch();

}


Output

C program for selection sort
Selection sort

No comments: