Friday, September 21, 2012

program for selection sort

c++program for selection sort..
#include<conio.h>
#include<iostream.h>

#include<stdio.h>
void main()
{
int i,j,n,p,a[20],s,t;
clrscr();
cout<<"Enter the limit\n";
cin>>n;
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}

for(i=0;i<n;i++)
 {
 s=a[i];
 p=i;
 for(j=i+1;j<n;j++)
 {
 if(a[j]<s)
  {
  s=a[j];
  p=j;
  }
 }

  t=a[p];
  a[p]=a[i];
  a[i]=t;

  }

for(i=0;i<n;i++)
  {
  cout<<a[i]<<"  ";
  }


getch();
}


The Selection Sort Algorithm

Like bubble sort, selection sort is implemented with one loop nested inside another. This suggests that the efficiency of selection sort, like bubble sort, is n 2 . To understand why this is indeed correct, consider how many comparisons must take place. The first iteration through the data require n - 1 comparisons to find the minimum value to swap into the first position. Because the first position can then be ignored when finding the next smallest value, the second iteration requires n - 2 comparisons and third requires n - 3 . This progression continues as follows:
(n - 1) + (n - 2) + ... +2 + 1 = n(n - 1)/2 = O(n 2)
Unlike other quadratic tests, the efficiency of selection sort is independent of the data. Bubble sort, for example, can sort sorted and some nearly-sorted lists in linear time because it is able to identify when it has a sorted list. Selection sort does not do anything like that because it is only seeking the minimum value on each iteration. Therefore, it cannot recognize (on the first iteration) the difference between the following two sets of data: 1 2 3 4 5 6 7 8 9 and 1 9 8 7 6 5 4 3 2. In each case, it will identify the 1 as the smallest element and then go on to sorting the rest of the list. Because it treats all data sets the same and has no ability to short-circuit the rest of the sort if it ever comes across a sorted list before the algorithm is complete, insertion sort has no best or worst cases. Selection sort always takes O(n 2) operations, regardless of the characteristics of the data being sorted.

No comments:

Post a Comment