C Program to Sort an Array using Merge Sort - Source Code, Output & Execution Flow

C Program to Sort an Array using Merge Sort

This tutorial explains c program to sort an array using merge sort with C source code, sample output, and step-by-step execution flow.

#include <stdio.h>
void merge(int a[], int l, int m, int r) {
    int i = l, j = m + 1, k = 0, temp[50];
    while (i <= m && j <= r) temp[k++] = (a[i] <= a[j]) ? a[i++] : a[j++];
    while (i <= m) temp[k++] = a[i++];
    while (j <= r) temp[k++] = a[j++];
    for (i = l, k = 0; i <= r; i++, k++) a[i] = temp[k];
}
void mergeSort(int a[], int l, int r) {
    if (l < r) {
        int m = (l + r) / 2;
        mergeSort(a, l, m);
        mergeSort(a, m + 1, r);
        merge(a, l, m, r);
    }
}
int main() {
    int a[] = {38, 27, 43, 3, 9}, i;
    mergeSort(a, 0, 4);
    for (i = 0; i < 5; i++) printf("%d ", a[i]);
    return 0;
}
3 9 27 38 43

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.

Sai Kishore Randhi, author
About the author

Sai Kishore Randhi

Embedded systems, VLSI, and chip design

Sai Kishore writes about embedded systems, VLSI, chip design, and the programming concepts behind modern hardware.

View LinkedIn profile ↗