Saturday, 10 May 2014

Selection Sort

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
                int i,j,k,n,c,a[20],min;
                clrscr();
                printf("$$$ SELECTION SORT $$$");
                printf("\nEnter the array limit:");
                scanf("%d",&n);
                printf("Enter array elements:");
                for(i=0;i<n;i++)
                {
                                scanf("%d",&a[i]);
                }
                printf("Passes of selection sort:\n");
                for(i=0;i<n-1;i++)
                {
                                min=i;;
                                for(j=i+1;j<n;j++)
                                {
                                                if(a[min]>a[j])
                                                {
                                                                min=j;
                                                }
                                }
                                if(i!=min)
                                {
                                                k=a[i];
                                                a[i]=a[min];
                                                a[min]=k;
                                }
                                printf("\nPass=%d,\t",i+1);
                                for(c=0;c<n;c++)
                                {
                                                printf("%d\t",a[c]);
                                }
                }
                printf("\nThe sorted elements are:\t");
                for(i=0;i<n;i++)
                {
                                printf("%d\t",a[i]);
                }
                getch();
}

OUTPUT:

$$$ SELECTION SORT $$$
Enter the array limit:       6
Enter array elements:    23           78           45           8              32           56
Passes of selection sort:
Pass=1,                 8              78           45           23           32           56
Pass=2,                 8              23           45           78           32           56
Pass=3,                 8              23           32           78           45           56
Pass=4,                 8              23           32           45           78           56
Pass=5,                 8              23           32           45           56           78
The sorted elements are:             8              23           32           45           56           78

No comments:

Post a Comment