Insertion sort in C: solved exercise

  2 minutes

If you are searching for an insertion sort in C solved exercise, this post gives you both the implementation and the reasoning.

The idea is similar to sorting cards in your hand: take the next value and insert it into the correct position within the already sorted part.

Implement insertion sort to sort an integer array in ascending order.

#include <stdio.h>

void insertion_sort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];
        int j = i - 1;

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

int main(void) {
    int a[] = {12, 11, 13, 5, 6};
    int n = (int)(sizeof(a) / sizeof(a[0]));

    insertion_sort(a, n);

    for (int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    return 0;
}
5 6 11 12 13
  • Forgetting to store the current value in key before shifting.
  • Writing the final position incorrectly (a[j + 1] = key).
  • Using j > 0 instead of j >= 0.
  • Ignoring that runtime cost mainly comes from shifts.

Insertion sort is useful when:

  • arrays are small,
  • input is nearly sorted,
  • you want a clear baseline before shell sort or merge sort.

It is also common in beginner assignments and junior interview screens.

If you want a complete path with progressive difficulty:

Yes. It is one of the best first algorithms to learn loops, comparisons, and shifts.

Worst and average case: O(n²). Best case (nearly sorted input): O(n).

Trace small arrays manually and count shifts per iteration. That makes performance behavior very clear.