Skip to content
Laviyx Learn

Try

DS Lab · Experiment 10

Merge sort

CSortingJNTUH R22 · CS306PC

Aim

To write a C program that sorts a list of integers in ascending order using merge sort, showing each merge step.

Algorithm

  1. Read n and the n elements into an array.
  2. Merge sort (low, high): if low < high, find mid = (low + high) / 2.
  3. Merge sort the left half a[low..mid] and the right half a[mid+1..high].
  4. Merge the two sorted halves: compare the front elements of both halves and copy the smaller one into a temporary array. Repeat until one half is used up.
  5. Copy the remaining elements of the other half into the temporary array.
  6. Copy the temporary array back into a[low..high].
  7. After sorting, print the array.

Program

C
#include <stdio.h>

#define MAX 50

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

/* Merge the sorted parts a[low..mid] and a[mid+1..high] */
void merge(int a[], int low, int mid, int high) {
    int temp[MAX];
    int i = low, j = mid + 1, k = 0;

    while (i <= mid && j <= high) {
        if (a[i] <= a[j]) {
            temp[k++] = a[i++];
        } else {
            temp[k++] = a[j++];
        }
    }
    while (i <= mid) {              /* left half has elements left */
        temp[k++] = a[i++];
    }
    while (j <= high) {             /* right half has elements left */
        temp[k++] = a[j++];
    }
    for (k = 0, i = low; i <= high; i++, k++) {
        a[i] = temp[k];
    }

    printf("Merged a[%d..%d]: ", low, high);
    print_array(a + low, high - low + 1);
}

void merge_sort(int a[], int low, int high) {
    if (low < high) {
        int mid = (low + high) / 2;
        merge_sort(a, low, mid);
        merge_sort(a, mid + 1, high);
        merge(a, low, mid, high);
    }
}

int main(void) {
    int a[MAX], n;

    printf("Enter number of elements (1-%d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of elements\n");
        return 1;
    }
    printf("Enter %d elements: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &a[i]) != 1) {
            printf("Invalid input\n");
            return 1;
        }
    }

    merge_sort(a, 0, n - 1);

    printf("Sorted list: ");
    print_array(a, n);
    return 0;
}

Output

Output
Enter number of elements (1-50): 7
Enter 7 elements: 38 27 43 3 9 82 10
Merged a[0..1]: 27 38 
Merged a[2..3]: 3 43 
Merged a[0..3]: 3 27 38 43 
Merged a[4..5]: 9 82 
Merged a[4..6]: 9 10 82 
Merged a[0..6]: 3 9 10 27 38 43 82 
Sorted list: 3 9 10 27 38 43 82 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

Each "Merged" line shows one part of the array right after its two sorted halves were merged. The parts grow from two elements to the whole array.

print_array(a + low, ...) passes the address of a[low], so the function prints only that part of the array. Using <= when the two front elements are equal takes the one from the left half first, which keeps equal elements in their original order (merge sort is stable).

Common mistakes

  • Forgetting the two loops that copy the leftover elements after the main merge loop, so some elements are lost.

  • Forgetting to copy temp back into a. The array then never changes, and later merges work on unsorted halves.

  • Splitting as merge_sort(a, low, mid - 1) and merge_sort(a, mid, high). With two elements, mid equals low, so the second call never gets smaller and the recursion does not end.

  • Starting the copy-back at a[0] instead of a[low].

Viva questions

Try to answer each one aloud before you open it.

  • How does merge sort work?

    It is a divide and conquer method. It splits the array into two halves, sorts each half recursively, and then merges the two sorted halves into one sorted array.

  • What is the time complexity of merge sort?

    O(n log n) in the best, average and worst cases. The array is halved about log n times, and each level of merging does O(n) work.

  • What is its space complexity?

    O(n) extra space for the temporary array used while merging, plus O(log n) for the recursion stack.

  • Is merge sort stable?

    Yes. When two elements are equal, the one from the left half is copied first, so equal elements keep their original order.

  • When is merge sort preferred over quick sort?

    When a guaranteed O(n log n) worst case or a stable sort is needed, and for sorting linked lists or data too large for memory (external sorting).

Learn the concepts

All Data Structures Lab experiments →