Saturday, August 20, 2011

Sort an array using Insertion sort.

//Program to sort an array using Insertion sort.
#include<stdio.h>
#include<conio.h>
void main()
{
  int *a,n,i,temp,k,j;
  clrscr();
  printf("\nEnter the no. of element in the array: ");
  scanf("%d",&n);
  a=(int *)malloc(n*sizeof(int));
  printf("\nEnter the values of %d elements: ",n);
  for(i=0;i<n;i++)
  {
  scanf("%d",&a[i]);
  }
  for(i=1;i<n;i++)
  {
   temp=a[i];
    for(j=0;j<i;j++)
    {
     if(temp<a[j])
     {
       for(k=i;k>j;k--)
    a[k]=a[k-1];
    a[j]=temp;
    break;
     }
    }
  }
  printf("\nThe sorted array is:");
  for(i=0;i<n;i++)
  {
     printf("\n %d ",a[i]);
  }
  getch();
}

Previous Next Home
0 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More