Monday, 20 June 2011

Insertion sort program in c



#include <stdio.h>

void insertion_sort();
int a[50],n;

main()
{
  int i;
  
  printf("\nEnter size of an array: ");
  scanf("%d", &n);
  
     printf("\nEnter elements of an array:\n");
  for(i=0; i<n; i++)
    scanf("%d", &a[i]);
  
     insertion_sort();
  
     printf("\n\nAfter sorting:\n");
  for(i=0; i<n; i++)
    printf("\n%d", a[i]);
    
 
}

void insertion_sort()
{
  int j, k, temp;
  
     for(j=1; j<n; j++)
     {
    temp = a[j];
          k = j-1;
      
          while (k>=0 && a[k]>temp)
    {
      a[k+1] = a[k];
      k--;
    }
          a[k+1] = temp;
     }    
}
Editing & Program by 'Shojib'

No comments:

Post a Comment