# selection sort in c

what is selection sort:-

In this sorting technique you can sort an array by repeatedly finding the min element and putting this element at the starting of the array.

example:-

you have to sort the array :-   2   32  4  65  3  7  then

step 1:-   first we have to find the min in this array which is 2 at put this in the beginning

2  32  4 65 3 7

step 2:- find the min in unsorted array( except first element because first element sorted in in  step 1)  which is 3 so put in the beginning of unsorted array

2  3  32  4  65  7

step 3:- find the min in unsorted array (which is  4) and put it in the beginning of the       unsorted  array

2  3  4 32  65  7

step 4:- find the min in unsorted array (which is  7) and put it in the beginning of the       unsorted  array

2  3  4  7  32  65

step 4:- find the min in unsorted array (which is  32) and put it in the beginning of the       unsorted  array

2  3  4  7  32  65

This is the sorted array.

Note:- the number  of step required for the sorting is equal to n-1 where n is the size of the array.

Code:-

#include<stdio.h>
int main()
{
int n,a[100],tem,i,j,min;
printf("Enter the number of element in the arary\n");
scanf("%d",&n);
printf("Enter the element of the array\n");
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
// selection sort
for(i=0;i<n-1;i++)
{
min=a[i];
for(j=i+1;j<n;j++)
{
if(min>a[j])
{
tem=a[j];
a[j]=min;
min=tem;
}
}
a[i]=min;
}
printf("The sorted array is:-\n");
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

Output:-

Enter the number of element in the array
5
Enter the element of the array
32 2 54 3 4 65
The sorted array is:
2 3 4 32 54