C Example Code2026-03-202 min read
Learn Insertion Sort in C with step-by-step element insertion trace, full runnable source code, and time complexity comparison explained.
How Insertion Sort Works
Insertion Sort works the way you sort playing cards in your hands: you iterate through the array, pick the current element (key), and insert it into its correct relative position within the already-sorted prefix on the left by shifting larger elements one position to the right.
C Code Implementation
c (ISO Standard)#include <stdio.h> void insertionSort(int arr[], int n) { for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; /* Shift elements greater than key to one position ahead */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = {12, 11, 13, 5, 6}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original Array:\n"); printArray(arr, n); insertionSort(arr, n); printf("Sorted Array (Insertion Sort):\n"); printArray(arr, n); return 0; }
Sample Output
text (ISO Standard)Original Array: 12 11 13 5 6 Sorted Array (Insertion Sort): 5 6 11 12 13
Complexity Analysis
- Best Case Time:
O(n)(When array is already sorted). - Worst & Average Case Time:
O(n²)(When sorted in reverse). - Space Complexity:
O(1)in-place auxiliary memory. - Stability: Stable (preserves order of identical elements).
Related Sorting Algorithms
- Compare with Selection Sort in C.
- Review array indexing in Arrays in C Programming.