Friday, 27 April 2012

Program for Selection Sort in C

#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,k,a[100],n,temp,pos;
printf("Enter the number of elements in your array: \n\n");
scanf("%d",&n);
printf("Now, enter the elements of the array that you want to sort: \n\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Here is the UNSORTED ARRAY:\n\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(a[pos]>a[j])
{
pos=j;  //For finding the smallest element in the remaining array - the array after the ith element!
}
}
if(pos!=i) //If both the numbers to be swapped are NOT equal - then, execute the following code!
{
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
}
printf("\n\nThe array after step %d -- ",i+1);
for(k=0;k<n;k++)
{
printf("%d ",a[k]);
}
}
getch();
return 0;
}

No comments:

Post a Comment