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

Merge Sort: Recursive splitting

Merge Sort: Recursive splitting

What you'll learn: How the "divide" phase of Merge Sort uses recursion to break a large, messy array into single-element pieces.

The "Divide and Conquer" Strategy

Merge Sort is a classic example of a "divide and conquer" algorithm. Imagine you are handed a massive, tangled pile of 1,000 socks and told to sort them by color. Looking at the whole pile is overwhelming. However, if you split that pile into two piles of 500, then split those into 250, and keep going until you are holding just one sock in each hand, the task becomes simple. A single sock is, by definition, "sorted."

In C, we achieve this through recursion—a function that calls itself with a smaller portion of the array until it hits a base case.

Splitting to the Base Case

To split an array, we find the middle index (mid). We then tell the function to handle the left half (from low to mid) and the right half (from mid + 1 to high).

The "base case" is the moment the subarray has only one element. In C terms, this happens when the low index is no longer less than the high index. At that point, the recursion stops diving deeper and begins the process of returning back up the chain.

The Recursive Structure

Here is how we represent this "splitting" logic in C. Note that this code focuses strictly on the division; the actual "merging" happens after these calls.

void mergeSort(int arr[], int low, int high) {
    // Base case: If the section has 1 or 0 elements, it's already "sorted"
    if (low < high) {
        // Find the midpoint to split the array in two
        int mid = low + (high - low) / 2;

        // Recursively split the left half
        mergeSort(arr, low, mid);

        // Recursively split the right half
        mergeSort(arr, mid + 1, high);

        // After splitting, the "Merge" step would go here
        // merge(arr, low, mid, high);
    }
}

Why split first?

You might wonder why we spend so much effort breaking things apart. By recursively splitting, we create a "tree" of operations. The computer doesn't have to figure out how to sort 1,000 items at once; it only ever has to worry about merging two smaller, already-sorted lists together. The splitting phase is the essential preparation that turns a complex problem into a series of tiny, manageable ones.

Key takeaway

Recursive splitting breaks a large array into individual elements, reaching a base case where every sub-array is one element long and therefore "sorted."