Selection Sort
Selection sort is a sorting algorithm, specifically an in-place comparison sort. This sorting algorithm based upon finding successively the record with the largest sort key and putting it in the correct position, then the record with the next largest key, etc.

Strategy

  • Choose the largest/smallest item in the array and place
    the item in its correct place
  • Choose the next larges/next smallest item in the array
    and place the item in its correct place.
  • Repeat the process until all items are sorted.

Algorithm

Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Properties

It is not a  Stable algorithm i.e does change the relative order of elements with equal keys

Best , Average,Worst Cases

Worst complexity: n^2
Average complexity: n^2
Best complexity: n^2
Space complexity: 1

 

Program

//Selection Sort
#include<iostream.h>
#include<conio.h>
// Display For Array
void display(int number[],int size){
   for(int i=0;i<size;i++){
      cout<<" "<<number[i];
      (size==i+1)? cout<<".": cout<<",";
   }
}
//Selection Sort
void selection_sort(int array[],int size){
   for(int i=0;i<size;i++){
      for(int j=i+1;j<size;j++){
         if(array[i]>array[j]){
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
         }
      }
   }
}

void main(){
   clrscr();
   int size = 8;
   int array[10]={45,65,55,75,12,59,89,49,62,20}; // Array
   cout<<"\n ------Selection Sort------";
   cout<<"\n Before Sorting \n";
   display(array,size);
   cout<<"\n After Sorting \n";
   //Selection Sort
   selection_sort(array,size);
   display(array,size);
   getch();
}

Output 

Live Demo

demo

(Visited 299 times, 1 visits today)
Share with Friends :