Write a C program for Insertion Sort.

for j = 2 to A.length
	 key = A[j]
	 i = j - 1
	 while i > 0 and A[i] > key
  A[i + 1] = A[i]
	 i = i - 1
	 A[i + 1] = key
Figure: Insertion Sort

#include <stdio.h>

int main()
{
//!showSort(array)
  int n, array[5], c, d, t, flag = 0;

  printf("Enter number of elements\n");
  scanf("%d", &n);

  printf("Enter %d integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  for (c = 1 ; c <= n - 1; c++) {
    t = array[c];

    for (d = c - 1 ; d >= 0; d--) {
      if (array[d] > t) {
        array[d+1] = array[d];
        flag = 1;
      }
      else
        break;
    }
    if (flag)
      array[d+1] = t;
  }

  printf("Sorted list in ascending order:\n");

  for (c = 0; c <= n - 1; c++) {
    printf("%d\n", array[c]);
  }

  return 0;
}

Enter number of elements
5
Enter 5 integers
5
4
3
2
1
Sorted list in ascending order:
1
2
3
4
5

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.