Selection Sort of N numbers: C

Selection sort is a sorting technique which is inefficient on large list of elements. Its simple and easy to understand.

In selection sort, first we select one element and compare it with the rest of the elements. If the compared element is smaller than the selected element, then those numbers are sorted. This approach is continued till the last element in the array index.

The number of iterations is 1 less than the array size.
i.e., if the user enters array size as 5, then there will be 4 iterations.

Below is an example:

Lets assume, user has entered the array size as 5.
and entered 13, 0, -2, 8, 3 as array elements.


First Iteration:



In first iteration, a[0] is selected. and is compared with a[1], a[2], a[3] and a[4]. and is swapped with the least value in the array.


Second Iteration:



In the second iteration, we leave off a[0] and select a[1] and compare it with the rest of the elements in the array i.e., a[2], a[3] and a[4]. and swap the least value with a[1]

Third Iteration:



In third iteration, we select a[2] and compare it with a[3], a[4] and swap the least value to a[2]


Forth Iteration:



In forth iteration, we select a[3] and compare it with a[4] and swap the least value.

At the end of 4 iterations all array elements are sorted.

Video Tutorial: Selection Sort of N numbers: C



YouTube Link: https://www.youtube.com/watch?v=NWLPmRdIPBA [Watch the Video In Full Screen.]



Since the array index starts from 0, and we need not compare the last element in the array with any other elements, we iterate the outer loop from 0 to N-2.
We iterate the inner loop from i+1 till N-1.

Source Code: Selection Sort of N numbers: C

#include<stdio.h>
#include<conio.h>
 
void main()
{
int a[20], i, j, N, temp;
clrscr();
 
printf("Enter the size of the array\n");
scanf("%d", &N);
 
printf("Enter %d elements\n", N);
for(i=0; i<n ; i++)
 scanf("%d", &a[i]);
 
for( i=0; i<=N-2; i++ )
 for( j=i+1; j<=N-1; j++ )
  if(a[i] > a[j])
  {
     temp = a[i];
     a[i] = a[j];
     a[j] = temp;
  }
 
         printf("\nSorted Array:\n");
  for(i=0; i < n ; i++)
   printf("\n%d", a[i]);
 
   getch();
 
}

Output:
Enter the size of the array
5
Enter 5 elements
13
0
-2
8
3
Sorted Array:
-2
0
3
8
13

View Comments

    • n-1 because, there is no more element to compare the last element with!
      n-2 because, in the last iteration comparison is between last and last but one element. And there is no further pair to compare.

      Analyze above images, and you'll understand. You're not alone, many of us din't understand these kind of logic in the first attempt. So take your time, but keep trying until you understand.