Sort elements using insertion sort - C Program

C program to sort 'n' numbers using insertion sort.

Solution:

  • In insertion sort, the second element in an array is compared with the element that is present before it i.e first element. If the second element is smaller than the first, insert it at the position of first element.
  • In the next step, third element of array is compared with the elements which appear before it. i.e first & second. This process continues until the end of array. At the end, all the elements in the array will be sorted.

#include<stdio.h>
int main()
{
      int i,j,size,t,a[30];
      printf("\tInsertion sort\n");
      printf("-----------------------------------\n");
      printf(" How many numbers you want to sort?: ");
      scanf("%d",&size);
      printf("\n Enter %d numbers: \n",size);
      for(i=0;i<size;i++)
      {
            scanf("%d",&a[i]);
      }
      for(i=1;i<=size-1;i++)
      {
            t=a[i];
            j=i-1;
            while((t<a[j])&&(j>=0))
            {
                  a[j+1]=a[j];    //moves element forward
                  j=j-1;
            }
            a[j+1]=t;    //insert element in proper place
      }
      printf("\n Sorted numbers after using insertion sort: \n\n");
      for(i=0;i<size;i++)
      {
            printf("  %d",a[i]);
      }
      return 0;
}


Output:

insertion sort