w3resource logo

:

C Programming Exercises

C Exercises: Insertion sort algorithm

C Programming Searching and Sorting Algorithm: Exercise-4 with Solution

Write a C program to sort a list of elements using the insertion sort algorithm.

Note:
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than other algorithms such as quicksort, heapsort, or merge sort.

Pictorial presentation - Insertion search algorithm :

C programming Insertion sort algorithm

Sample Solution:

Sample C Code:

#include<stdio.h>
  void main()
  {
  int  arra[10],i,j,n,array_key;
  printf("Input  no. of values in the array: \n");
  scanf("%d",&n);
  printf("Input  %d array value(s): \n",n);
  for(i=0;i<n;i++)
  scanf("%d",&arra[i]);
  
  /* Insertion Sort  */
  for (i = 1; i <  n; i++)
  {
  array_key =  arra[i];
  j = i-1;
  
  while (j >=  0 && arra[j] > array_key)
  {
  arra[j+1] = arra[j];
  j = j-1;
  }
  arra[j+1] =  array_key;
  }
  printf("Sorted  Array: \n");
  for (i=0; i <  n; i++)
  printf("%d  \n", arra[i]);
  }

Flowchart:

Flowchart: C Programming - Insertion sort

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.