C Insertion Sort

Intermediate
6 min read
Updated: Nov 2026
1 example

Inserting into a Sorted Prefix

Insertion sort keeps a sorted prefix. For each new element (the key) it shifts larger prefix elements one place right and drops the key into the gap, like sorting playing cards in your hand. It is O(n^2) worst case, O(n) on nearly sorted input, stable, in place, and excellent for small arrays.

Remember
for (i = 1; i < n; i++) {
    key = a[i]; j = i - 1;
    while (j >= 0 && a[j] > key) { a[j + 1] = a[j]; j--; }
    a[j + 1] = key;
}

Cheat Sheet

Keep these facts handy while you work with Insertion Sort in C.

TopicDetail
BestO(n) sorted input
WorstO(n^2) reverse sorted
StableYes
Great forSmall or nearly sorted data

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Merge Sort.

Example 1 — Trace each insertion

Sort 64, 25, 12, 22, 11.

C
#include <stdio.h>

int main(void) {
    int a[] = {64, 25, 12, 22, 11};
    int n = 5;

    for (int i = 1; i < n; i++) {
        int key = a[i], j = i - 1;
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;

        printf("i=%d:", i);
        for (int k = 0; k < n; k++) printf(" %d", a[k]);
        printf("\n");
    }
    return 0;
}

How It Works

  1. Each step inserts a[i] into the sorted prefix to its left.
  2. Larger elements shift one slot right to open a gap.
  3. The final insertion of 11 shifts the whole prefix.

Edge Cases & Pitfalls

Check these before relying on Insertion Sort in real programs.

bound

Checking j before a[j]

Test j >= 0 first in the condition to avoid reading a[-1].

stable

Using >= in the shift test

It shifts equal items and breaks stability.

Key Takeaways

  • Shift, then insert.
  • Great on nearly sorted data.
  • Stable and in place.

One line: Insertion sort keeps a sorted prefix.

Frequently Asked Questions

Each element only shifts a short distance, so total work approaches O(n).
As the base case of hybrid sorts for small partitions, such as in many library sort implementations.
Continue with "C Merge Sort" next. Split the array in half, sort each half, and merge them. The C Sorting Algorithms hub lists every topic in order.

Next: Merge Sort

Split the array in half, sort each half, and merge them.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful