VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-for-insertion-sort/

⇱ C Program For Insertion Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program For Insertion Sort

Last Updated : 12 Dec, 2025

Insertion Sort is a simple comparison-based sorting algorithm that builds the final sorted list one element at a time.

  • It divides the list into sorted and unsorted part. Initially, the first element is already considered sorted, while the rest of the list is considered unsorted.
  • The algorithm then iterates through each element in the unsorted part, picking one element at a time, and inserts it into its correct position in the sorted part.
  • It is easy to implement and works well for small datasets.

Let's take an example of array arr = {12, 11, 13, 5, 6} that we need to sort in ascending order.

Insertion Sort Algorithm in C

  • Start with the second element (index 1) as the key.
  • Compare the key with the elements before it.
  • If the key is smaller than the compared element, shift the compared element one position to the right.
  • Insert the key where the shifting of elements stops.
  • Repeat steps 2-4 for all elements in the unsorted part of the list.

Output
Unsorted array: 12 11 13 5 6 
Sorted array: 5 6 11 12 13 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Advantages of Insertion Sort

  • Insertion sort is that it is an in-place sorting algorithm.
  • It is simple to implement which is great for small datasets.
  • Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially sorted.
  • Best-case scenario only requires O(n) time.

Note: The algorithm typically shows only the final sorted result, not the progress after each iteration, making it harder to trace or debug.

Comment
Article Tags: