Course contentsShow
← C
Lesson 1054 of 1,21914. Data Structures in CFree lesson

Merge Sort: The Merge function

Merge Sort: The Merge function

What you'll learn: How to combine two sorted sub-arrays into a single, larger sorted array using a temporary workspace.

The Strategy: Two Decks, One Table

Imagine you have two stacks of playing cards on a table. The catch? Both stacks are already sorted (e.g., Ace to King). Your goal is to merge them into one big sorted stack.

You look at the top card of both stacks. Whichever is smaller goes face down into your new pile. You repeat this, always comparing the current "top" of both stacks, until one stack is empty. Finally, you just toss the remaining cards from the non-empty stack onto the new pile. This is the heart of Merge Sort.

The merge function in C

In C, we don't have physical cards; we have an array. The merge function takes a range within an array, treats it as two halves, and uses a temporary array to build the result.

void merge(int arr[], int left, int mid, int right) {
    int i = left;      // Starting index for the left half
    int j = mid + 1;   // Starting index for the right half
    int k = 0;         // Starting index for the temp array
    int temp[right - left + 1];

    // Compare elements from both halves and move the smaller one
    while (i <= mid && j <= right) {
        if (arr[i] <= arr[j]) {
            temp[k++] = arr[i++];
        } else {
            temp[k++] = arr[j++];
        }
    }

    // If cards remain in the left half, copy them
    while (i <= mid) {
        temp[k++] = arr[i++];
    }

    // If cards remain in the right half, copy them
    while (j <= right) {
        temp[k++] = arr[j++];
    }

    // Move the sorted temp array back into the original array
    for (i = 0; i < k; i++) {
        arr[left + i] = temp[i];
    }
}

Why the temporary array?

You might wonder: "Why not just swap elements inside the original array?"

The problem is that if you move a small element from the right side into the left side without a workspace, you would overwrite (and lose) the elements currently sitting in the left side. The temporary array acts as a "waiting room," allowing us to organize the elements perfectly before we move them back into their permanent home.

Key takeaway

The Merge function works by comparing the smallest available elements of two sorted sub-arrays and placing the winner into a temporary buffer.