Selection Sort



What is Sorting?

Sorting is a process of arranging a list of values either in ascending order or in descending order.

Selection Sort Algorithm

Selection Sort algorithm is used to arrange a list of elements in a particular order (Ascending or Descending). In selection sort, We select the element that is at the first position in the list and it is compared with all the other elements in the list. Whenever we find an element smaller than the selected element then both the elements are swapped. So that by the end of first iteration process, the smallest element in the list comes to the first position. Repeat the same process with all the positions in the list such that all the elements in the list are arranged in ascending order.

The selection sort algorithm is performed using following steps...

  • Step 1: Select the first element of the list (i.e., Element at first position in the list).
  • Step 2: Compare the selected element with all the other elements in the list.
  • Step 3: In every comparision, if any element is found smaller than selected element (for Ascending order), then those two elements are swapped.
  • Step 4: Repeat the same procedure with the next position in the list till the entire list is sorted.

Selection sort main logic

Following is the sample code for selection sort logic...

//Selection sort logic

  for(i=0; i list[j])
	   {
               temp=list[i];
               list[i]=list[j];
               list[j]=temp;
           }
      }
  }
  

Example

Consider the following list of elements

Selection Sort

Program to implement Selection Sort Algorithm using C.

#include<stdio.h>
#include<conio.h>

void main(){

  int size,i,j,temp,list[100];
  clrscr();

  printf("Enter the size of the List: ");
  scanf("%d",&size);

  printf("Enter %d integer values: ",size);
  for(i=0; i<size; i++)
      scanf("%d",&list[i]);
  
  //Selection sort logic

  for(i=0; i<size; i++){
      for(j=i+1; j<size; j++){
           if(list[i] > list[j])
	   {
               temp=list[i];
               list[i]=list[j];
               list[j]=temp;
           }
      }
  }

  printf("List after sorting is: ");
  for(i=0; i<size; i++)
      printf(" %d",list[i]);

  getch();
}