Wednesday, 7 November 2012

Selection Sort in c++


SELECTION SORT
Arranging the list of numbers or words (name, grade etc.) in ascending or in descending order is called Sorting. This is done by following various logical techniques like Bubble, Insertion or Selection sort technique. Among these three, Selection Sort  logical technique is the most easiest and generally followed by us manually also. 
To know about Bubble Sort technique click here : http://schawla00.blogspot.com

 To explain this in detail, consider a list of five number to be sorted in ascending order kept at different five places  are : 

The main logic to be followed is :

1.    Find the smallest of all the numbers kept from 2nd place till the last place, if this number smaller than the number at 1st place exchange (SWAP) the numbers on those places
2.    Now, find smallest kept between 3rd place till the last place & if this number is smaller than number at 2nd place exchange or do nothing.
3.    Similarly follow the same procedure till the number at second last place is checked
4.    The list finally made is Sorted List in Ascending order.

Algorithm for the same is (Ascending order sorting):
1)    Read the list of ‘n’ elements and store them in the array at their position                           (in c++ , 0  to n-1)
2)    Let i=0
3)    Find the location containing smallest element in the array located in the position              (i+1) to n and mark this position with the variable min_location.
4)    Exchange (or Swap) the ith element with the element stored in min_location.
5)    Increase value of i by 1 (i=i+1)
6)    If (i<n-1) goto 3 else goto 7
7)    Show all elements of the sorted array.
8)    Stop.

 #include<iostream.h>
 void main()
 {
   int array[6] = {34, 12, 56,-8, 74, 35};
   int i, j, temp, min_location;
   clrscr();
   for(i=0; i<5; i++)
    {
              min_location = i;
              for(j=i+1; j<6; j++)
                 if(array [min_location]> array [j])
                   min_location = j;

       temp = array [min_location];
       array [min_location] = array [i];
       array [i] = temp;
      }


for(i=0; i<6; i++)
 cout<<"\n"<< array [i];
 }


















No comments:

Post a Comment