Program of Sorting using Selection Sort

The Selection sort technique is based upon the extension of the maximum/minimum technique. By means of a nest of for loop a pass through the array is made to locate the minimum value.

 

Once this is found, it is placed in the first position of the array(position 0). Another pass through the remaining elements is made to find the next smallest element, which is placed in the second position(position 1), and so on. Once  the next to last element is compared with the last element, all the elements have been sorted into ascending order(min to max).

/*Program of Sorting using Selection Sort*/

#include <stdio.h>

#define MAX 20

main()

{

                int ar[MAX], ii,jj,kk,n,temp,smallest;

                printf("Enter the no. of elements : ");

                scanf("%d",&n);

                for (ii = 0; ii < n; ii++)

                {

                    printf("Enter element %d : ",ii+1);

                                scanf("%d", &ar[ii]);

                }

                printf("Unsorted list is : \n");

                for (ii = 0; ii < n; ii++)

                                printf("%d ", ar[ii]);

                printf("\n");

                /*Selection sort*/

                for(ii = 0; ii< n - 1 ; ii++)

                {

                                /*Find the smallest element*/

                                smallest = ii;

                                for(kk = ii + 1; kk < n ; kk++)

                                {

                                                if(ar[smallest] > ar[kk])

                                                                smallest = kk ;

                                }

                                if( ii != smallest )

                                {

                                                temp = ar [ii];

                                                ar[ii] = ar[smallest];

                                                ar[smallest] = temp ;

                                }

                                printf("After Pass %d elements are :  ",ii+1);

                                for (jj = 0; jj < n; jj++)

                                                printf("%d ", ar[jj]);

                                printf("\n");

                }/*End of for*/

                printf("Sorted list is : \n");

                for (ii = 0; ii < n; ii++)

                                printf("%d ", ar[ii]);

                printf("\n");

}/*End of main()*/

Output.....

Program of Sorting using Selection Sort

About Us

Rekha SetiaRekha Setia is a passionate blogger of Extra Computer Notes. if you have any ideas or any request me @