Thursday, March 8, 2012

3. SELECTION SORT IN C

In computer science, a Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.









EXAMPLE:



64 25 12 22 11

11 25 12 22 64

11 12 25 22 64

11 12 22 25 64

11 12 22 25 64 

ALGORITHM:


The algorithm works as follows:
  1. Find the minimum value in the list
  2. Swap it with the value in the first position
  3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time)
Effectively, the list is divided into two parts: the sublist of items already sorted, which is built up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array. 



/* a[0] to a[n-1] is the array to sort */
int iPos;
int iMin;
 
/* advance the position through the entire array */
/*   (could do iPos < n-1 because single element is also min element) */
for (iPos = 0; iPos < n; iPos++) {
    /* find the min element in the unsorted a[iPos .. n-1] */
 
    /* assume the min is the first element */
    iMin = iPos;
    /* test against all other elements */
    for (int i = iPos+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 != iPos ) {
        swap(a, iPos, iMin);
    }
}



ANIMATION:


CODE:



/* WWW.CODE-AHOLIC.BLOGSPOT.IN- SELECTION SORT */
#include<stdio.h>
#include<conio.h>

void main()
{
int s,i,j,temp,a[20];
  printf("Enter total elements: ");
  scanf("%d",&s);
  printf("Enter %d elements: ",s);
  for(i=0;i<s;i++)
      scanf("%d",&a[i]);
  for(i=0;i<s;i++)
{
      for(j=i+1;j<s;j++)
{
            if(a[i]>a[j])
{
                temp=a[i];
              a[i]=a[j];
              a[j]=temp;
            }
      }
  }

  printf("After sorting is: ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  getch();
}

DOWNLOAD CODE