C Code for Selection Sort

Searching and sorting have been popular operations in elementry data structures. Although now a days many advanced sorting techniques are used to sort a set of data, the basic sorting methods are still popular and are the used frequently. Here C code for selection sort is given. The algorithm for selection sort is quite simple. In the first iteration, 1st element is compared against all the other elements (from array index 1 to array index n). In the second iteration 2nd element is compared with the elements from array index 2 to n. This process is repeated n-1 times.

The C code is as follows :


#include "stdio.h"

void main( )
{
	int arr[5] = { 25, 17, 31, 13, 2 } ;
	int i, j, temp ;
	for ( i = 0 ; i <= 3 ; i++ )
	{
		for ( j = i + 1 ; j <= 4 ; j++ )
		{
			if ( arr[i] > arr[j] )
			{
				temp = arr[i] ;
				arr[i] = arr[j] ;
				arr[j] = temp ;
			}
		}
	}

	printf ( "\n\nArray after sorting:\n") ;

	for ( i = 0 ; i <= 4 ; i++ )
		printf ( "%d\t", arr[i] ) ;
}


Related Posts

  • Share/Bookmark
You can leave a response, or trackback from your own site.

8 Responses to “C Code for Selection Sort”

  1. neha says:

    rlly working well!!

  2. Amit says:

    Thanks

  3. sonu says:

    very good and easy logic…………
    easy to understand your program……..

  4. chandrakant says:

    good

  5. Best code for Beginers.
    Good language and better skill used for student

  6. Vikash says:

    THANKS for providing easy logic.

  7. nitin jain says:

    #include
    #include
    int main()
    {
    int i,j,a[50],n;
    int iMin,temp;

    printf(“\nEnter size of the array: “);
    scanf(“%d”,&n);

    printf(“\nEnter %d elements in to the array: “,n);
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);

    /* advance the position through the entire array */
    /* (could do j < n-1 because single element is also min element) */
    for (j = 0; j < n-1; j++) {
    /* find the min element in the unsorted a[j .. n-1] */

    /* assume the min is the first element */
    iMin = j;
    /* test against elements after j to find the smallest */
    for ( i = j+1; i < n; i++) {
    /* if this element is less, then it is the new minimum */
    if (a[i] < a[iMin]) {
    /* found new minimum; remember its index */
    iMin = i;
    }
    }

    /* iMin is the index of the minimum element. Swap it with the current position */
    if ( iMin != j ) {

    temp=a[j];
    a[j]=a[iMin];
    a[iMin]=temp;
    }
    }

    printf("after sorting");
    for(i=0;i<n;i++)
    {
    printf("\n%d",a[i]);
    }
    getch();
    return 0;
    }

Leave a Reply

| Shop Free Cellular Phones at Bestincellphones.com. | Thanks to Best CD Rates, iCellPhoneDeals.com Offers Best Cell Phone Deals. and Incinerador De Grasa