Insertion Sort in C programming

Image result for c programming

Code:

   #include<stdio.h>
void insertionsort(int *, int);
int main(void)
{
  int n, a[20],i;
  printf("Enter the number of elements in the array\n");
  scanf("%d",&n);
  for (i=0;i<n;++i)
  {
    printf("Enter element %d\n",i+1);
    scanf("%d",&a[i]);
  }
  printf("Insertion sort.\narray before sorting:\n");
  for (i=0;i<n;i++)
    printf("%d ",a[i]);
  insertionsort(a,n);
  return 0;
}

void insertionsort(int *a, int size)
{
  int value, hole,i,j;
  for(i=1;i<size;++i)
  {
    value=a[i];
    hole=i-1;
    while(hole>=0 && a[hole]>value)
    {
      a[hole+1]=a[hole];
      hole=hole-1;
    }
    a[hole+1]=value;
    printf("\nAfter Iteration %d\n",i);
    for(j=0;j<size;j++)
      printf("%d ",a[j]);
}
  printf("\narray after sorting:\n");
  for(j=0;j<size;j++)
    printf("%d ",a[j]);
}

No comments