Monday, 7 April 2014

Data Structure C++ Code for Selection Sort

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[100],i,n,p,k,min,loc,temp;

cout<<"\n------------ SELECTION SORT ------------ \n\n";
cout<<"Enter No. of Elements=";
cin>>n;
cout<<"\nEnter Elements=\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}

for(p=0;p<n-1;p++)              // Loop for Pass: Here the loop is running from p=0 to p<n-1.
{                               // From 0 t0 n-1, its normal beacuse in C++ the counting starts from 0 so for 10 elements it will be 0 to 9.
                                // Here it is p<n-1 beacuase in selection sort we compare the first element with the rest of the elements n-1.
                                // As we are using C++, so the full array will be from 0 to n-1 and if we take out the first element for comparison
                                // then we have to run the loop till p<n-1 because the first element is already taken out for comparison.


min=a[p];                       // Element Selection
loc=p;

for(k=p+1;k<n;k++)              // Finding Minimum Value: Here the loop goes from p+1 to n, because the selected element will be compared with all the remaining
{                               // elements of the array.
if(min>a[k])
{
min=a[k];
loc=k;
}
}

temp=a[p];                        // Swap Selected Element and Minimum Value
a[p]=a[loc];
a[loc]=temp;

}

cout<<"\nAfter Sorting : \n";
for(i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
getch();
}

No comments:

Post a Comment