Saturday 21 September 2013

Saturday 21 September 2013

Program in c for Selection Sort


C program for Selection Sort:

Let’s sort this array in ascending order using selection sort algorithm. Bubble sort algorithm was based on repeated comparison of successive elements in an array and exchanging elements if necessary. In selection sort there is a slight difference. One element in the array (usually the first/last element) is assumed as the minimum/maximum of the whole array elements. Now all other members are compared against this assumed min/max element. Based on this comparisons result, exchanges are made between the min/max element and the other element. 
The selection sorting algorithm is also an inefficient one (just like Bubble sort). Selection sort requires 0.5 *(n*n-n) comparisons. The total number of comparisons required is almost same for both Bubble sorting and Selection sorting.


#include<stdio.h>
int 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]);
 //selection sort 
  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:\n ");
  for(i=0;i<s;i++)
      printf(" %d",a[i]);

  return 0;
}

Working of Selection sort:
The element in the first position is assumed to be minimum. It is then compared with other elements one by one (using the 2nd FOR loop). After the first pass of the first FOR loop, the minimum of the whole array (in this case 1) is placed in first position of the array. When the second pass of first FOR loop begins, the next element (i.e second element) is assumed to be minimum and the whole process repeats. 

Compiling the source code....
$gcc main.c -o demo -lm -pthread -lgmp -lreadline 2>&1

Executing the program....
$demo
Enter total elements: Enter 5 elements: 45 67 2 5 77
After sorting is:
  2 5 45 67 77

No comments:

Post a Comment