Insertion sort method in C
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.
Problem statement
Implement insertion sort to sort an integer array in ascending order.
C solution
#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;
}Expected output
5 6 11 12 13Common mistakes
- Forgetting to store the current value in
keybefore shifting. - Writing the final position incorrectly (
a[j + 1] = key). - Using
j > 0instead ofj >= 0. - Ignoring that runtime cost mainly comes from shifts.
Practical use
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.
Recommended next exercise
- Shell sort in C: solved exercise step by step
- Binary insertion sort in C: solved exercise
- Bubble sort in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is insertion sort in C good for beginners?
Yes. It is one of the best first algorithms to learn loops, comparisons, and shifts.
What is insertion sort complexity?
Worst and average case: O(n²). Best case (nearly sorted input): O(n).
How should I practice insertion sort effectively?
Trace small arrays manually and count shifts per iteration. That makes performance behavior very clear.