The perfect place for easy learning...

Data Structures

×

Topics List

Place your ad here

Selection Sort Algorithm

Selection Sort algorithm is used to arrange a list of elements in a particular order (Ascending or Descending). In selection sort, the first element in the list is selected and it is compared repeatedly with remaining all the elements in the list. If any element is smaller than the selected element (for Ascending order), then both are swapped. Then we select the element at second position in the list and it is compared with remaining all elements in the list. If any element is smaller than the selected element, then both are swapped. This procedure is repeated till the entire list is sorted.

Step by Step Process

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 other elements in the list.
  • Step 3: For every comparision, if any element is smaller than selected element (for Ascending order), then these two are swapped.
  • Step 4: Repeat the same procedure with next position in the list till the entire list is sorted.

Following is the sample code for selection sort...

Selection Sort Logic

//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;
           }
      }
  }

Example

Selection sort algorithm

Complexity of the Selection Sort Algorithm

To sort a unsorted list with 'n' number of elements we need to make ((n-1)+(n-2)+(n-3)+......+1) = (n (n-1))/2 number of comparisions in the worst case. If the list already sorted, then it requires 'n' number of comparisions.

Worst Case : O(n2)
Best Case : Ω(n2)
Average Case : Θ(n2)

Implementaion of Selection Sort Algorithm using C Programming Language

#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();
}

Output

Selection Search Program

Place your ad here
Place your ad here