ccompiler.inOnline C Compiler & Docs
C Example Code2026-03-202 min read

Learn Merge Sort in C with recursive splitting, array merging logic, full working source code, and guaranteed O(n log n) complexity.

Understanding Merge Sort

Merge Sort is an efficient, general-purpose, comparison-based divide-and-conquer sorting algorithm. It repeatedly divides an array into two halves until each sub-array has a single element, then systematically merges the sorted sub-arrays back together.


Complete C Implementation

c (ISO Standard)
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int left, int mid, int right) {
    int n1 = mid - left + 1;
    int n2 = right - mid;

    int L[n1], R[n2];

    for (int i = 0; i < n1; i++) L[i] = arr[left + i];
    for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];

    int i = 0, j = 0, k = left;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k++] = L[i++];
        } else {
            arr[k++] = R[j++];
        }
    }

    while (i < n1) arr[k++] = L[i++];
    while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int data[] = {38, 27, 43, 3, 9, 82, 10};
    int n = sizeof(data) / sizeof(data[0]);

    printf("Original array:\n");
    printArray(data, n);

    mergeSort(data, 0, n - 1);

    printf("Sorted array (Merge Sort):\n");
    printArray(data, n);

    return 0;
}

Sample Output

text (ISO Standard)
Original array:
38 27 43 3 9 82 10 
Sorted array (Merge Sort):
3 9 10 27 38 43 82 

Complexity Analysis

  • Time Complexity: O(n log n) guaranteed across Best, Average, and Worst cases.
  • Space Complexity: O(n) auxiliary memory for temp merge buffers.
  • Stability: Stable sorting algorithm.

Related C Examples & Tutorials