Written by Sai Sandeep Thota on December 25, 2012 in C > Programming

# Selection Sort C Code with Explanation

Selection Sort in C is a Basic Sorting Technique. Selection sort program is used to sort elements in ascending order, It is based on comparison and swapping method. To start sorting, We need to consider the first element[A] as the smallest and compare with the other elements present in the list. If the number less than the considered element is found, then the smallest number[B] is compared with the other elements and the elements are swapped accordingly by placing the smallest number at the index(first) position. We have written an easy selection sort C code below.

For example:

**5 3 9 7 2**

Step – 1: Consider 5 as the smallest and compare with 3.

Step – 2: As 3 is smaller than 5, Compare 3 with 9 => 3 is smaller.

Step – 3: Compare 3 with 7 => 3 is smaller.

Step – 4: Compare 3 with 2 => 2 is smaller. They are no elements left in the list. So swap 2 and 5.

Result after first Comparison will be:

**2 3 9 7 5**

After 5 comparisons we get the following sorted Order:

**2 3 5 7 9**

Its time complexity is O(n²) in all Best, Average and Worst cases. It is slow and suitable for sorting lists of small number of elements. Take a look at the simple program below.

/* C Program to Implement Selection Sort */
#include<conio.h>
#include<stdio.h>
#define max 50
void selsort(int, int[]);
void main()
{
int i, size, data[max];
clrscr();
printf("\nEnter no of Elements:");
scanf("%d",&size);
printf("\nEnter Elements:");
for(i=1;i<=size;i++)
scanf("%d",&data[i]);
printf("\nUnsorted data:\n");
for(i=1;i<=size;i++)
printf("%d\t",data[i]);
selsort(size, data);
getch();
}
void selsort(int n, int data[])
{
int i, j, min, temp;
printf("\nSorted List is:\n");
for(i=1;i<=n-1;i++)
{
min = i;
for(j=i+1;j<=n;j++)
{
if(data[j]<data[min])
min = j;
}
temp=data[i];
data[i]=data[min];
data[min]=temp;
}
for(i=1;i<=n;i++)
printf("\t%d",data[i]);
}

Output:

*Related*

Tagged as:
C Programs

Sai Sandeep has written **105** articles for us.

Programming. Networking. Photography.
You can follow me on : Facebook | Twitter | Google+ | Instagram

{ 0 comments… add one now }