Insertion Sorting in C

Hello Everyone!!

This is a simple post of Insertion Sorting Algorithm in Integer Array.  Insertion sort is taking successive elements in every iteration and comparing with previous elements. 



In first iteration, second element(301) is compared with first(99). If the second is smaller, then it will be swapped. In next iteration, third element(23) is compared firstly with second element(301) and then first element(99), if the third element is smaller than second, it will be swapped (Now the array is 99 23 301 10 1). Again second element(23) will be compared with first element(99). Repeatively, every element is compared with all other elements before it.

#include<stdio.h>


main()

{
int a[5];
int i,j,k;

  printf("Enter the elements of the array\n");

  for (i=0;i<5;i++) {
    printf("a[%d]\t",i);
    scanf ("%d",&a[i]);
  }
 printf("\n%d iteration\n\t",0);
 for (i = 0;i < 5;i++) {
      printf ("%d\t",a[i]);
 }
 for (j = 1;j < 5;j++) {
     k = a[j] ;
     printf("\n%d iteration\n\t",j);
     i = j-1;
     while((i >= 0) && (k < a[i])) {
           a[i+1] = a[i];
           a[i] = k;
           i--;
     }
     for (i=0;i<5;i++) {
          printf ("%d\t",a[i]);
     }
  } // for j loop

  printf("\n \nAfter Insertion Sorting\n");

  for (i=0;i<5;i++) {
    printf ("a[%d] %d\n",i,a[i]);
  }
}


Output 



Enter the elements of the array
a[0]    99
a[1]    301
a[2]    23
a[3]    10
a[4]    1

0 iteration
        99      301     23      10      1
1 iteration
        99      301     23      10      1
2 iteration
        23      99      301     10      1
3 iteration
        10      23      99      301     1
4 iteration
        1       10      23      99      301

After Selection Sorting
a[0] 1
a[1] 10
a[2] 23
a[3] 99
a[4] 301


Comments