C Program to Sort an Array Using Insertion Sort - Source Code, Output & Execution Flow

C Program to Sort an Array Using Insertion Sort

This C program sorts an array using insertion sort.

#include <stdio.h>
int main() {
    int a[] = {9, 5, 1, 4, 3};
    int n = 5, i, j, key;
    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;
    }
    for (i = 0; i < n; i++) printf("%d ", a[i]);
    return 0;
}
1 3 4 5 9

In this program, the input is read first when required, the core logic is applied step by step, and the final result is displayed using printf(). Follow the execution flow beside the code to understand how each statement contributes to the output.