Mastering Insertion Sort in C: Code, Logic, and Applications

Published: 13 Dec 2025 | Reading Time: 6 min read

Table of Contents

What This Blog Covers

This comprehensive guide provides:

Introduction

Sorting is a technique that facilitates the handling of data by making it more manageable and easily searchable. One simple and efficient way, particularly for small or almost sorted data, is Insertion Sort. Due to its straightforward logic and gradual execution, it is a favorite in C programming.

Insertion Sort in C works by placing each element in its correct position within a growing sorted part of the list. While not ideal for large datasets, it's perfect for beginners learning sorting basics.

In this blog, you'll learn how Insertion Sort works in C, its algorithm, use cases, and how it compares to other sorting methods.

What is Sorting?

Sorting refers to the process of arranging a set of items in a certain sequence, most often from the smallest to the largest (ascending) or from the largest to the smallest (descending). It plays a major role in enhancing the efficiency of other operations, for instance, searching, as it makes data more accessible and easier to find.

Common Sorting Algorithms

What is Insertion Sort in C?

Insertion Sort in C is a specific sorting algorithm that organizes data step by step. When implementing insertion sort in a C program, it picks one element at a time from an unsorted list and places it in the correct position within a growing sorted section. This process continues until all elements are sorted.

Characteristics of Insertion Sort

Insertion Sort Algorithm and Pseudocode

Insertion sort is a local, comparison-based sorting algorithm that builds the eventual sorted array one element at a time. The method first splits the array into two sub-lists: one sorted and one unsorted. Then, element by element, the algorithm takes the next element (the "key") from the unsorted sub-list and places it into the sorted sub-list at the proper position.

Algorithmic Paradigm

Step-by-Step Outline

  1. Start with the second element (index 1); the first element is considered sorted.
  2. For each element, store its value in a variable called "key."
  3. Compare the key with elements in the sorted sub-list (to its left).
  4. Shift elements that are larger than the key one position to the right.
  5. Place the key in the sorted sub-list where it belongs.
  6. Repeat until the entire array is sorted.

Pseudocode (Iterative Approach)

INSERTION_SORT(array):
    for e from 1 to length(array) - 1:
        key = array[e]
        f = e - 1

        while f >= 0 and array[f] > key:
            array[f + 1] = array[f]
            f = f - 1

        array[f + 1] = key

Explanation:

Pseudocode (Recursive Approach)

RECURSIVE_INSERTION_SORT(array, n):
    if n <= 1:
        return

    // Sort first n-1 elements
    RECURSIVE_INSERTION_SORT(array, n - 1)

    // Insert last element at its correct position
    key = array[n - 1]
    f = n - 2

    while f >= 0 and array[f] > key:
        array[f + 1] = array[f]
        f = f - 1

    array[f + 1] = key

Explanation:

Implementation Variations

Manual Walkthrough and Example of Insertion Sort

A manual walkthrough helps clarify how insertion sort operates on an array, step by step. Let's simulate the process with a concrete example.

Working Principle of Insertion Sort

Insertion sort is a simple, in-place, stable algorithm that gradually builds a sorted array from the unsorted one, by way of one element at a time. Its logic is very similar to how you would sort playing cards in your hand.

Example: Sorting an Array Step by Step

Suppose we want to sort the array:

a = [9, 5, 1, 4, 3]

We will use the insertion sort algorithm to arrange the elements in ascending order.

Step 1: The First Element

Step 2: Insert 5

Step 3: Insert 1

Step 4: Insert 4

Step 5: Insert 3

Summary Table

Step Action Resulting Array
1 Start [9, 5, 1, 4, 3]
2 Insert 5 [5, 9, 1, 4, 3]
3 Insert 1 [1, 5, 9, 4, 3]
4 Insert 4 [1, 4, 5, 9, 3]
5 Insert 3 [1, 3, 4, 5, 9]

Notes

Complexity Analysis of Insertion Sort in C

Knowing how efficient insertion sort is can be a deciding factor in whether to use it or not. Below you can find its time and space complexity described for different situations:

Time Complexity

Best Case (Already Sorted Input)

When the array is already sorted, insertion sort only compares each element once without shifting.

Time Complexity: O(n)

This linear running time occurs because the inner loop never moves elements; no shifting is needed.

Worst Case (Reverse-Sorted Input)

In the case where the input array is sorted in descending order, every new element will have to be compared and shifted all the way to the beginning of the already sorted part.

Time Complexity: O(n²)

The quadratic behavior is due to the fact that for each element, the algorithm makes the maximum possible number of comparisons and shifts.

Average Case (Random/Jumbled Order)

With random data, the insertion sort will typically have to shift about half of the already sorted elements for each new element.

Time Complexity: O(n²)

The number of operations grows rapidly with larger arrays, making it inefficient for big datasets.

Space Complexity

Auxiliary Space

Insertion sort is an in-place algorithm, i.e. it only needs a constant number of extra memory space.

Space Complexity: O(1)

The only extra variable typically used is the key for comparison and insertion.

Worst-Case Space Complexity

Remains O(1), as no additional data structures are used regardless of input arrangement.

Complexity Summary Table

Scenario Time Complexity Space Complexity
Best Case (sorted) O(n) O(1)
Average Case O(n²) O(1)
Worst Case (reversed) O(n²) O(1)

Key Points

Implementation of Insertion Sort in C

Insertion Sort is the one which goes on building the sorted array step by step by comparing the current element with the previous ones and then inserting the element into the correct place. The method is quite natural and is good enough when the dataset is small or almost sorted.

Method 1: Basic Implementation

Below is a simple insertion sort C code implementation along with a detailed explanation:

#include <stdio.h>

void insertionSort(int arr[], int size) {
    for (int i = 1; i < size; i++) {
        int key = arr[i], j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

int main() {
    int arr[] = {7, 2, 5, 3, 1};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Before sorting: ");
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);

    insertionSort(arr, size);

    printf("\nAfter sorting: ");
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);

    return 0;
}

Explanation

Insertion Sort in C works by picking elements one by one and placing them in their correct position by shifting larger elements to the right. It starts from the second element and continues until the entire array is sorted. Insertion Sort C Code implements nested loops for comparing and inserting elements efficiently.

Output

Before sorting: 7 2 5 3 1
After sorting: 1 2 3 5 7

Time and Space Complexity

Method 2: Recursive Implementation

The following code demonstrates how Insertion Sort can be implemented recursively using the C programming language.

#include <stdio.h>

void recursiveInsertionSort(int arr[], int size) {
    if (size <= 1)
        return;

    recursiveInsertionSort(arr, size - 1);

    int lastElement = arr[size - 1];
    int j = size - 2;

    while (j >= 0 && arr[j] > lastElement) {
        arr[j + 1] = arr[j];
        j--;
    }
    arr[j + 1] = lastElement;
}

int main() {
    int arr[] = {8, 4, 2, 6, 1};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Before Sorting: ");
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);

    recursiveInsertionSort(arr, size);

    printf("\nAfter Sorting: ");
    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);

    return 0;
}

Explanation

This code indicates Insertion Sort in C using a recursive approach. Insertion Sort C Code works by first sorting a smaller part of the array and then placing the last element in its correct position by shifting larger elements forward.

Output

Before Sorting: 8 4 2 6 1
After Sorting: 1 2 4 6 8

Time and Space Complexity

Practical Applications and Use Cases of Insertion Sort in C

The insertion sort algorithm in C language benefits most from applications where its adaptability nature leads to faster running time, which is especially true for the best-case scenario or partially sorted data. Despite the fact that its average and worst cases are O(n²), as a result, it is still useful in various practical situations.

1. Partially Sorted or Nearly Sorted Data

An insertion sort algorithm is close to perfect for situations when the data is almost pre-sorted.

2. Small Arrays or Subarrays

Insertion sort beats more complex methods when working with tiny datasets.

3. Real-Time or Online Insertion

It is a good solution when data is available one item at a time.

4. Educational and Testing Scenarios

It is an algorithm that serves as the base concept of algorithm fundamentals and is thus most commonly referred to when teaching this field.

5. Handling Random or Small Data Samples

While inefficient for large arrays, insertion sort is practical for quick sorting of random order small lists.

Bottom Line

By understanding these use cases, you can confidently choose insertion sort in C whenever you need a simple, stable, and efficient solution for small or nearly sorted datasets, real-time incremental sorting, or as a reliable component in hybrid sorting strategies.

Comparison with Other Sorting Algorithms

Insertion Sort belongs to the family of O(n²) comparison-based sorting algorithms, but its adaptive behavior makes it faster than similar algorithms (like Bubble Sort) when the data is nearly sorted. Unlike divide-and-conquer algorithms such as Merge Sort and Quick Sort, insertion sort works in-place and is easier to implement, but performs poorly on large datasets. There exist a few advanced variants, like Binary Insertion Sort and Shell Sort, which reduce the number of comparisons or jumps, and they are extensively used in hybrid algorithms (Timsort, Introsort) as a result of its small subarray efficiency.

The table below gives a comparative overview of insertion sort and several common sorting algorithms, thereby emphasising differences in approach, complexity, adaptiveness, and typical use cases.

Algorithm Approach/Paradigm Time Complexity (Best / Avg / Worst) Space Complexity Typical Use Cases / Notes
Insertion Sort Incremental, In-place O(n) / O(n²) / O(n²) O(1) Small or nearly sorted arrays; subroutine in hybrid sorts
Bubble Sort In-place, Exchange O(n) / O(n²) / O(n²) O(1) Educational purposes are rarely used in practice
Selection Sort In-place, Selection O(n²) / O(n²) / O(n²) O(1) Small datasets, when write operations are costly
Shell Sort In-place, Gap Insertion O(n log n) / O(n^1.5) / O(n²) O(1) Improved insertion sort for larger arrays
Merge Sort Divide-and-Conquer O(n log n) / O(n log n) / O(n log n) O(n) Large datasets, stable sort needed
Quick Sort Divide-and-Conquer O(n log n) / O(n log n) / O(n²) O(log n) General-purpose, fast for large datasets
Heap Sort Heap-based, In-place O(n log n) / O(n log n) / O(n log n) O(1) Large datasets, when constant space is needed
Binary Insertion Sort Incremental, Binary Search O(n log n) / O(n²) / O(n²) O(1) Fewer comparisons than regular insertion sort, but same number of shifts
Hybrid Approaches (e.g., TimSort, IntroSort) Adaptive/Hybrid O(n) / O(n log n) / O(n log n) O(n) Real-world libraries, switch to insertion sort for small subarrays

Key Differences and Notes

Advantages and Disadvantages of Insertion Sort

Insertion sort comes with a mix of strengths and limitations, making it highly effective in some scenarios while inefficient in others, especially as data size grows.

Advantages

Disadvantages

Conclusion

Insertion Sort in C is an excellent example that visually and logically walks through the principles of sorting algorithms. It performs fine on small or almost sorted datasets, and since it is simple to implement, it is perfect for those who are learning. Though it is less efficient than a fast algorithm like Quicksort or Mergesort when it comes to large data, it is still a good stepping stone for understanding the essential concepts of sorting.

Key Points to Remember

Frequently Asked Questions

1. What is insertion sort, and how does it work?

Insertion sorting is a method for sorting numbers by arranging them one at a time. It picks an item from the unsorted section and places it where it belongs in the sorted part, shifting larger numbers to the right when needed.

2. Is insertion sort stable?

Yes, the insertion sort is stable. This means if two elements have the same value, they will stay in the same order as they were in the original list.

3. What is the time complexity of insertion sort?

In the worst and average cases, insertion sort takes O(n²) time, which makes it slow for big lists. However, if the data is almost sorted, it can run in O(n) time.

4. How do you implement insertion sort in C?

In C, insertion sort is generally implemented with a loop. Every number is checked against the ones before it and, if necessary, it is placed in the correct position. This means that nested loops are used to compare and shift elements.

5. What are the benefits of using insertion sort?

Simple to understand and code, uses very little extra memory (O(1)), and works well on small or nearly sorted lists.

6. When is insertion sort better than other sorting methods?

It is best for small datasets or lists that are already mostly sorted. It's also useful when new data keeps coming in and needs quick sorting.

7. Can insertion sort be done with recursion?

Yes, it can be written in a recursive way by sorting part of the list first and then inserting the next element into the right spot. This follows the same logic as the regular version but uses function calls instead of loops.


Source: NxtWave - https://www.ccbp.in/blog/articles/insertion-sort-in-c