Friday 7 September 2012

selection sort in c

#include <stdio.h>

void main(void)
{
    int a[30],i,j,k,n,pos,min,temp;

    clrscr();
    printf("\t\t\tProgram on Selection Sort");
    printf("\n\nEnter How many numbers you want to Sort : ");
    scanf("%d",&n);
    printf("\nEnter %d numbers : ",n);
    for (i=0;i<n;i++)
         scanf("%d",&a[i]);

    for (i=0;i<n-1;i++)
       {

/*    Finding minimum number to arrange elements in Ascending Order    */
         min = a[i];
         pos = i;
         for (j=i+1;j<n;j++)
        {
           if (min>a[j])
             {
            min = a[j];
            pos = j;
             }
        }

/*    Exchange the found minimum with current unsorted position    */

        temp = a[i];
        a[i] = a[pos];
        a[pos] = temp;

        printf("\nAfter Pass %d :",i+1);
        for (k=0;k<n;k++)
           printf("%5d",a[k]);
       }

/*    The list is in Ascending Order    */

    printf("\n\nThe list in Ascending order is :\n");
    for (i=0;i<n;i++)
       printf("%5d",a[i]);
    getch();
    printf("\nPress any key to end...");
}

No comments:

Post a Comment