Saturday 6 December 2014

C Program for Selection Sort Algorithm

Selection Sort:

             A Selection sort algorithm is one of Internal Sorting technique. It sorts the list by selecting the largest element in the unsorted list and places it at the appropriate position.In Each position, the largest element in the list is placed at appropriate position. If there are 'n' elements in the list, we require (n-1) passes.


Program:

#include <stdio.h>
#include<conio.h>
int main()
{
            int a[100], n, i, j, k,temp;
            clrscr();
            printf("\nEnter Number of elements:");
            scanf("%d", &n);
            printf("\nEnter %d of Elements:", n);
            for( i = 0 ; i < n ; i++ )
           {
                 scanf("%d", &a[i]);
           }
           for( i = 0 ; i < n - 1; i++ )
          {
                 k = i;
                 for ( j = i + 1 ; j < n ; j++ )
                {
                 if ( a[k] > a[j] )
                 k = j;
                 }
                if ( k != i )
                {
                 temp = a[i];
                 a[i] = a[k];
                 a[k] = temp;
                 }
           }
           printf("\nSorted list in ascending order:");
           for ( i = 0 ; i < n ; i++ )
           {
                    printf("\n%d", a[i]);
           }
           getch( );
}


Output:

Enter Number of Elements:4

Enter 4 of Elements:0
3
2
10

Sorted list in ascending order:
0
2
3
10




0 comments:

Post a Comment