Merge Sort Program In C Language

5 min read

A merge sort program in C language is a classic example of how the divide-and-conquer strategy can be used to sort data efficiently. Merge sort works by repeatedly dividing an array into smaller parts, sorting those parts, and then merging them back together in the correct order. It is widely used in computer science education because it is easy to understand, reliable, and has a consistent time complexity of O(n log n). Whether you are learning C programming, preparing for interviews, or studying sorting algorithms, a merge sort program in C language is an important concept to master.

Introduction to Merge Sort

Sorting is the process of arranging data in a specific order, such as ascending or descending. Many programs need sorting, including database systems, search tools, data analysis applications, and operating systems. Common sorting algorithms include bubble sort, selection sort, insertion sort, quick sort, heap sort, and merge sort.

Some disagree here. Fair enough.

Merge sort is especially useful because it guarantees efficient performance even in the worst case. Unlike some algorithms whose speed can change depending on the input, merge sort consistently performs at O(n log n). This makes it a strong choice when predictable performance matters.

Basically where a lot of people lose the thread.

The main idea behind merge sort is simple:

  1. Divide the array into two halves.
  2. Recursively sort each half.
  3. Merge the two sorted halves into one sorted array.

This approach is called divide and conquer because a large problem is broken into smaller subproblems, solved separately, and then combined Practical, not theoretical..

How Merge Sort Works

Merge sort follows three major steps:

1. Divide

The array is split into two halves until each subarray contains only one element. A single-element array is already sorted, so this becomes the stopping point for recursion.

To give you an idea, consider this array:

12, 11, 13, 5, 6, 7

Merge sort divides it like this:

[12, 11, 13] [5, 6, 7]
[12] [11, 13] [5] [6, 7]
[12] [11] [13] [5] [6] [7]

2. Conquer

Each smaller subarray is sorted. Even so, since merge sort keeps dividing the array, eventually every subarray has one element. At that point, the algorithm begins merging It's one of those things that adds up. Simple as that..

3. Merge

The merge step combines two sorted arrays into one larger sorted array. This is the most important part of merge sort.

Take this: merging:

[11, 12] and [13]

produces:

[11, 12, 13]

Finally, the sorted halves are merged together to produce the complete sorted array:

[5, 6, 7, 11, 12, 13]

Complete Merge Sort Program in C Language

The following is a complete merge sort program in C language. It sorts an integer array in ascending order using recursion and a merge function It's one of those things that adds up..

#include 
#include 

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

    int *leftArray = malloc(n1 * sizeof(int));
    int *rightArray = malloc(n2 * sizeof(int));

    if (leftArray == NULL || rightArray == NULL) {
        printf("Memory allocation failed\n");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < n1; i++) {
        leftArray[i] = arr[left + i];
    }

    for (int j = 0; j < n2; j++) {
        rightArray[j] = arr[mid + 1 + j];
    }

    int i = 0;
    int j = 0;
    int k = left;

    while (i < n1 && j < n2) {
        if (leftArray[i] <= rightArray[j]) {
            arr[k] = leftArray[i];
            i++;
        } else {
            arr[k] = rightArray[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
        arr[k] = left

```c
    // Copy any remaining elements of leftArray, if there are any
    while (i < n1) {
        arr[k] = leftArray[i];
        i++;
        k++;
    }

    // Copy any remaining elements of rightArray, if there are any
    while (j < n2) {
        arr[k] = rightArray[j];
        j++;
        k++;
    }

    // Release dynamically allocated memory
    free(leftArray);
    free(rightArray);
}

/* Recursive function to perform merge sort on a subarray arr[left..right] */
void mergeSort(int arr[], int left, int right) {
    if (left < right) {
        /* Find the middle point to divide the array into two halves */
        int mid = left + (right - left) / 2;

        /* Recursively sort the first and second halves */
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);

        /* Merge the sorted halves */
        merge(arr, left, mid, right);
    }
}

/* Utility function to print an array */
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

/* Main function to demonstrate merge sort */
int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int arrSize = sizeof(arr) / sizeof(arr[0]);

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

    mergeSort(arr, 0, arrSize - 1);

    printf("Sorted array: \n");
    printArray(arr, arrSize);

    return 0;
}

Analysis and Characteristics

Time Complexity

  • Best case: O(n log n) – even if the input is already sorted, merge sort still divides and merges, avoiding the O(n²) pitfall of algorithms like bubble sort.
  • Worst case: O(n log n) – the division always produces balanced sub‑problems, guaranteeing consistent performance.
  • Average case: O(n log n) – the same as best and worst cases, making merge sort highly predictable.

Space Complexity

Merge sort requires additional memory proportional to the size of the input because it creates temporary left and right sub‑arrays during the merge step. The auxiliary space is O(n). This trade‑off is often acceptable when stable sorting and guaranteed performance are priorities.

Stability

The implementation above is stable: equal elements retain their relative order after sorting. This property is valuable in scenarios where sorting by multiple keys is required (e.g., sorting by last name and then by first name).

Use Cases

  • Large datasets: When dealing with arrays too big for recursion stack limits, merge sort can be adapted to work with linked lists or external storage.
  • When stability matters: Database operations, sorting of complex records, and any situation where the original order of equal keys must be preserved.
  • Parallel processing: The divide‑and‑conquer nature makes it amenable to parallel execution on multi‑core systems.

Limitations

  • Extra memory: The O(n) auxiliary space can be a drawback for memory‑constrained environments.
  • Overhead for small arrays: For very small inputs, the constant factors (allocation, copying) may outweigh the benefits of O(n log n) behavior. Hybrid algorithms (like Timsort) often switch to insertion sort for tiny sub‑arrays.

Conclusion

Merge sort stands out as a reliable, consistent sorting algorithm that guarantees O(n log n) performance regardless of input order. Its divide‑and‑conquer strategy, combined with a stable merging process, makes it a go‑to choice for many real‑world applications where predictable runtime and order preservation are essential. While it incurs a modest memory overhead, the trade‑off is frequently justified by its robustness and scalability, especially when handling large or partially ordered datasets Simple, but easy to overlook..

Fresh Stories

Hot off the Keyboard

Others Liked

If This Caught Your Eye

Thank you for reading about Merge Sort Program In C Language. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home