C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort

Sorting is one of the most common and essential operations in computer programming. It helps organize data so that it can be easily searched, analyzed, or displayed in an orderly fashion. Whether you’re arranging student grades, sorting prices on an online store, or managing a list of names, sorting algorithms are everywhere. They form the foundation of efficient data processing.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Among all sorting algorithms, Merge Sort stands out for its efficiency and elegance. It’s a classic example of the “divide and conquer” approach, which means it breaks a big problem into smaller parts, solves each part, and then combines the results. Merge Sort divides an array into two halves, sorts them separately, and then merges them together in a sorted manner. What makes it special is that it guarantees good performance even for large datasets, unlike simpler algorithms like Bubble Sort or Insertion Sort, which slow down with big lists.

Merge Sort is widely used in situations where efficiency and stability matter — for instance, in sorting large files or when building complex data structures like linked lists or binary trees. Let’s explore how Merge Sort works in C++ using different approaches and understand why it’s one of the most powerful sorting algorithms you can learn.

Program 1: Basic Merge Sort using Recursion

This first program shows the standard and most common way to implement Merge Sort in C++. It uses recursion to break down the array into smaller pieces and then merges them in a sorted order.

#include <iostream>

using namespace std;

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];
            i++;

        } else {

            arr[k] = R[j];
            j++;

        }

        k++;

    }

    while (i < n1) {

        arr[k] = L[i];
        i++;
        k++;

    }

    while (j < n2) {

        arr[k] = R[j];
        j++;
        k++;

    }

}

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);

    }

}

int main() {

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

    mergeSort(arr, 0, n - 1);

    cout << "Sorted array: ";

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    cout << endl;

    return 0;

}

This program uses a recursive function called mergeSort() that splits the array into halves until each half contains only one element. Then, the merge() function combines these smaller sorted parts into one sorted array. It’s like dividing a problem into smaller, easier pieces and solving each one step by step. For beginners, this approach helps you clearly see how recursion can simplify complex problems. Merge Sort’s time complexity is O(n log n), which makes it far more efficient than algorithms like Bubble Sort and Selection Sort for large datasets.

Program 2: Merge Sort using Iteration (Without Recursion)

While recursion is the most common way to write Merge Sort, it can also be implemented using iteration. This version avoids recursive calls and works in a bottom-up manner, gradually merging smaller sections of the array until everything is sorted.

#include <iostream>

using namespace std;

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 mergeSortIterative(int arr[], int n) {

    for (int curr_size = 1; curr_size < n; curr_size *= 2) {

        for (int left_start = 0; left_start < n - 1; left_start += 2 * curr_size) {

            int mid = min(left_start + curr_size - 1, n - 1);
            int right_end = min(left_start + 2 * curr_size - 1, n - 1);

            merge(arr, left_start, mid, right_end);

        }

    }

}

int main() {

    int arr[] {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);

    mergeSortIterative(arr, n);

    cout << "Sorted array (iterative): ";

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    cout << endl;

    return 0;

}

This version removes recursion entirely and uses loops to manage the merging process. It starts by merging pairs of small arrays (of size 1), then merges larger and larger sections until the whole array is sorted. It’s useful for beginners who want to understand how sorting can be done step by step without recursion. It’s also beneficial for situations where recursion may be limited, such as in systems with restricted memory.

Program 3: Merge Sort for Strings

Merge Sort can also be used to sort strings alphabetically. This example shows how you can apply the same logic to a list of words instead of numbers.

#include <iostream>
#include <string>

using namespace std;

void merge(string arr[], int left, int mid, int right) {

    int n1 = mid - left + 1;
    int n2 = right - mid;

    string 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(string 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);

    }

}

int main() {

    string arr[] {"Banana", "Apple", "Mango", "Cherry", "Peach"};
    int n = sizeof(arr) / sizeof(arr[0]);

    mergeSort(arr, 0, n - 1);

    cout << "Sorted words alphabetically: ";

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    cout << endl;

    return 0;

}

Here, Merge Sort is applied to an array of strings. Since C++ allows comparison of strings using relational operators like < and >, the same sorting logic works perfectly for words. The result is a neatly alphabetized list of words. This shows how Merge Sort is not limited to numbers — it can handle any data type that can be compared.

Program 4: Merge Sort in Descending Order

Sometimes we need to sort data in descending order — for example, when displaying top scores or ranking results from highest to lowest. This version of Merge Sort modifies the comparison condition to achieve that.

#include <iostream>

using namespace std;

void mergeDescending(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];
            i++;

        } else {

            arr[k] = R[j];
            j++;

        }

        k++;

    }

    while (i < n1) {

        arr[k] = L[i];
        i++;
        k++;

    }

    while (j < n2) {

        arr[k] = R[j];
        j++;
        k++;

    }

}

void mergeSortDescending(int arr[], int left, int right) {

    if (left < right) {

        int mid = left + (right - left) / 2;

        mergeSortDescending(arr, left, mid);
        mergeSortDescending(arr, mid + 1, right);
        mergeDescending(arr, left, mid, right);

    }

}

int main() {

    int arr[] {15, 3, 27, 12, 8, 20};
    int n = sizeof(arr) / sizeof(arr[0]);

    mergeSortDescending(arr, 0, n - 1);

    cout << "Sorted array in descending order: ";

    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    cout << endl;

    return 0;

}

The logic is the same as the standard Merge Sort, except for one key difference: the comparison inside the mergeDescending() function now checks for >= instead of <=. This ensures that larger numbers come before smaller ones, giving you a descending order result. This small but important change shows how flexible the Merge Sort algorithm can be.

Frequently Asked Questions (FAQ)

Here are some common questions beginners often ask about Merge Sort in C++.

Q1: What is Merge Sort in C++?
Merge Sort is a divide-and-conquer sorting algorithm that splits an array into halves, sorts each half, and then merges them together in sorted order.

Q2: Why is Merge Sort better than Bubble Sort or Insertion Sort?
Merge Sort is more efficient because it has a time complexity of O(n log n), while Bubble Sort and Insertion Sort take O(n²) time for large datasets.

Q3: Does Merge Sort use recursion?
Yes, in most implementations, Merge Sort uses recursion to divide the array into smaller parts. However, it can also be written iteratively using loops.

Q4: Is Merge Sort a stable sorting algorithm?
Yes, Merge Sort is stable, meaning it maintains the relative order of equal elements — an important feature for sorting records or data structures.

Q5: Where is Merge Sort used in real life?
Merge Sort is used in applications that handle large datasets or require stable sorting, such as database management, file sorting, and data analysis tools.

Conclusion

Merge Sort is one of the most efficient and elegant sorting algorithms you can learn in C++. It uses the divide-and-conquer approach to break a problem into smaller, manageable parts and then merges them back together in sorted order. Its O(n log n) time complexity makes it far better than simpler algorithms like Bubble Sort or Selection Sort for larger datasets.

In this article, we explored several ways to write a C++ Merge Sort program — the classic recursive version, an iterative version without recursion, and even one that sorts strings alphabetically. Each version shows how flexible and powerful this algorithm can be when applied to different data types and scenarios.

If you’re just starting your programming journey, try experimenting with the code, change the predefined data, and print intermediate results to see how the array divides and merges. The more you practice, the better you’ll understand how sorting algorithms like Merge Sort form the backbone of efficient programming.

Scroll to Top