Sorting
Insertion Sort
Build the sorted prefix one item at a time, shifting larger values right until the current key can be inserted.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this C DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.c
#include <stdio.h>
int main(void) {
int arr[] = {5, 1, 4, 2, 8};
int n = 5;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
printf("[");
for (int i = 0; i < n; ++i) {
if (i > 0) printf(", ");
printf("%d", arr[i]);
}
printf("]\n");
return 0;
}
Complexity
- Time: O(n^2) worst and average, O(n) best
- Space: O(1)
- Stable: yes
Implementation notes
- C stores
int arr[] = {5, 1, 4, 2, 8}as a fixed local array inmain; this source usesint n = 5rather than asizeoflength calculation. - The outer loop is
for (int i = 1; i < n; ++i). Each pass copiesarr[i]into the scalarkeybefore any shifts overwrite that slot. int j = i - 1stays signed so thewhile (j >= 0 && arr[j] > key)bound can stop before index-1; there is no helper function and no array pointer decay.- Shifts mutate the same stack array with
arr[j + 1] = arr[j], thenarr[j + 1] = keywrites the saved value into the opened slot. - The trace records
[5, 1, 4, 2, 8], then[1, 5, 4, 2, 8],[1, 4, 5, 2, 8], and[1, 2, 4, 5, 8]; the8pass does not move. - Output is formatted manually with
printf("["), comma-separatedprintf("%d", arr[i]), andprintf("]\n"). Visible memory is the stack array plus scalar locals; visible mutation is only the in-place array shifts and key placement.
sorted prefix
Positions before the scan index are already sorted.
shifting
Larger values move one slot right to make room for the key.