BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Insertion Sort Program in C

Last Updated: December 1, 2024 by Chaitanya Singh | Filed Under: C Programs

Insertion sort algorithm picks elements one by one and places it to the right position where it belongs in the sorted list of elements. In the following C program we have implemented the same logic.

Before going through the program, lets see the steps of insertion sort with the help of an example.
Input elements: 89  17  8  12  0
Step 1: 89  17  8  12  0 (the bold elements are sorted list and non-bold unsorted list)
Step 2: 17  89  8  12  0 (each element will be removed from unsorted list and placed at the right position in the sorted list)
Step 3: 8  17  89  12  0
Step 4: 8  12  17  89  0
Step 5: 0  8  12  17  89

C Program – Insertion Sort implementation

#include<stdio.h>
int main(){

   /* Here i & j for loop counters, temp for swapping,
    * count for total number of elements, number[] to
    * store the input numbers in array. You can increase
    * or decrease the size of number array as per requirement
    */
   int i, j, count, temp, number[25];

   printf("How many numbers u are going to enter?: ");
   scanf("%d",&count);

   printf("Enter %d elements: ", count);
   // This loop would store the input numbers in array
   for(i=0;i<count;i++)
      scanf("%d",&number[i]);

   // Implementation of insertion sort algorithm
   for(i=1;i<count;i++){
      temp=number[i];
      j=i-1;
      while((temp<number[j])&&(j>=0)){
         number[j+1]=number[j];
         j=j-1;
      }
      number[j+1]=temp;
   }

   printf("Order of Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}

Output:
insertion_sort_output_cmd

As you can observe in the output that we have entered 6 integer numbers in a random order and the above C program sorted them in ascending order by using the logic of insertion sort algorithm.

Top Related Articles:

  1. C Program to concatenate two strings without using strcat
  2. Ultimate Collection of C Programs: Source Code with Outputs
  3. C Program to find greatest of three numbers
  4. C Program to arrange numbers in ascending order
  5. Selection Sort Program in C

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap