# C Program for Implementation of Selection Sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It sorts an array by finding the minimum element in every iteration. This algorithm finds the lowest element in the array and place it at first position in first iteration, second lowest element in second iteration and so on. Selection sort algorithm is given below with example. C program is also given below to implement Selection sort algorithm.

The best thing about Selection Sort is that it takes maximum O(n) swaps unlike Bubble sort which may take more swap operations. Therfore, this algorithm is efficient when memory writing operation is costly.

Time complexity of Selection Sort is: O(n^2)

Algorithm:

step 1: For i = 1 to n-1   /*where n is the size of the array */
step 2:        set: min_index=1    /*here we took starting index as 1 */
step 3:        For j=i+1 to n
step 4:                    If arr[j]<arr[min_index]
step 5:                              set:  min_index=j
step 6:                    EndIf
step 7:        EndFor
step 8:        swap  (arr[i] and swap[min_index])
step 9: EndFor
step 10. Exit.

Example:

Let arr[] ={ 12, 4, 6, 13, 2}

Pass 1, i=0:  { 2 , 4, 6, 13, 12 }
Pass 2, i=1:  { 2 , 4, 6, 13, 12 }
Pass 3, i=2:  { 2 , 4, 6, 13, 12 }
Pass 4, i=3:  { 2 , 4, 6, 12, 13 }

C Program for Implementation of Selection Sort:
```#include <stdio.h>
#define MAX 100
int arr[MAX],n;
void selection_sort();
int main()
{
int i;

printf("\nEnter the total number of elements: ");
scanf("%d",&n);

printf("\nEnter the elements of the array: \n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

printf("\nOriginal Array is: \n");
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}

selection_sort();

printf("\n\nArray after sorting: \n");
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}

printf("\n");
return 0;
}
void selection_sort()
{
int i,j,min_index,temp;
for(i=0;i<n-1;i++)
{
min_index=i;
for(j=i+1;j<n;j++)
{
if(arr[j]<arr[min_index])
{

min_index=j;
}

}
temp=arr[min_index];
arr[min_index]=arr[i];
arr[i]=temp;
}
}```

OUTPUT: