Merge sort

Lesson 2 of 5 · Sorting

Merge sort divides an array into two halves, sorts each half (recursively) and then merges them into one sorted array. It runs in O(n log n) time and finishes a million numbers in a fraction of a second.

Before you start: prerequisites – simple sorting algorithms, introduction to recursion.
How to learn: type in and run every example, and solve the tasks at the end on your own first; open the hints and the solution only after that. All programs are in C++.

First step: merging two sorted arrays

The key part of the algorithm is merging two already sorted arrays. We look at the first elements of both arrays, copy the smaller one into the result and move on in the array it was taken from. When one array runs out, we copy the rest of the other.

Merging the arrays {3, 5, 10} and {-34, 16}
ABWe takeResult
3 5 10-34 16-34 (from B)-34
3 5 10163 (from A)-34 3
5 10165 (from A)-34 3 5
101610 (from A)-34 3 5 10
–16the rest of B-34 3 5 10 16
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n, m;
    cin >> n;
    vector<int> a(n);
    for (int &x : a) cin >> x;
    cin >> m;
    vector<int> b(m);
    for (int &x : b) cin >> x;

    vector<int> c;
    int i = 0, j = 0;
    while (i < n && j < m) {          // while both arrays have elements
        if (a[i] <= b[j]) c.push_back(a[i++]);
        else c.push_back(b[j++]);
    }
    while (i < n) c.push_back(a[i++]); // the rest of array a
    while (j < m) c.push_back(b[j++]); // the rest of array b

    for (int x : c) cout << x << " ";
    cout << endl;
    return 0;
}

Each element is copied exactly once, so merging runs in O(n + m) time.

The algorithm: divide, sort, merge

  1. If the array has one element, it is already sorted (the base case of the recursion).
  2. Divide the array into a left half a[l..m] and a right half a[m+1..r], where m = (l + r) / 2.
  3. Recursively sort the left and the right half.
  4. Merge the two sorted halves.
[38 27 43 3 9 82 10]
[38 27 43 3]        [9 82 10]          splitting
[38 27] [43 3]      [9 82] [10]
[38][27][43][3]     [9][82][10]
[27 38] [3 43]      [9 82] [10]        merging
[3 27 38 43]        [9 10 82]
[3 9 10 27 38 43 82]
#include <iostream>
#include <vector>
using namespace std;

vector<int> a, tmp;   // tmp is the auxiliary array for merging

void mergeSort(int l, int r) {
    if (l >= r) return;               // one element: already sorted
    int m = (l + r) / 2;
    mergeSort(l, m);                  // sort the left half
    mergeSort(m + 1, r);              // sort the right half

    // merging a[l..m] and a[m+1..r] into tmp[l..r]
    int i = l, j = m + 1, k = l;
    while (i <= m && j <= r) {
        if (a[i] <= a[j]) tmp[k++] = a[i++];
        else tmp[k++] = a[j++];
    }
    while (i <= m) tmp[k++] = a[i++];
    while (j <= r) tmp[k++] = a[j++];
    for (k = l; k <= r; k++) a[k] = tmp[k];   // copy the merged part back into a
}

int main() {
    int n;
    cin >> n;
    a.resize(n);
    tmp.resize(n);
    for (int &x : a) cin >> x;

    mergeSort(0, n - 1);

    for (int x : a) cout << x << " ";
    cout << endl;
    return 0;
}
Why a[i] <= a[j] and not <? When the elements are equal, we take the one from the left half first. That way equal elements keep their order and the algorithm is stable.

Video: merge sort

The video shows the procedure step by step on an example.

Why O(n log n)?

The array is halved until the parts have length 1. Going from n elements to 1 takes about log₂ n halvings – that is the number of levels. On each level of merging, all n elements are copied in total. So the total work is about n · log₂ n.

nn² (selection, bubble)n · log₂ n (merge sort)
1 0001 000 000about 10,000
100 0001010about 1,700,000
1 000 0001012about 20,000,000

Merge sort always runs in O(n log n), whatever the arrangement of the elements, but it uses extra memory for an auxiliary array of size n.

Application: counting inversions

An inversion is a pair of positions i < j for which a[i] > a[j]. The number of inversions shows how “far” the array is from sorted (and it equals the number of swaps made by bubble sort). Counting all pairs takes O(n²), but merge sort does it along the way:

when during merging we take an element from the right half (a[j] < a[i]), it is smaller than all remaining elements of the left half, a[i..m]. Each of them forms an inversion with it, so we add m − i + 1 to the number of inversions.

#include <iostream>
#include <vector>
using namespace std;

vector<int> a, tmp;

long long countInversions(int l, int r) {
    if (l >= r) return 0;
    int m = (l + r) / 2;
    long long count = countInversions(l, m) + countInversions(m + 1, r);
    int i = l, j = m + 1, k = l;
    while (i <= m && j <= r) {
        if (a[i] <= a[j]) tmp[k++] = a[i++];
        else {
            count += m - i + 1;          // a[j] is smaller than all a[i..m]
            tmp[k++] = a[j++];
        }
    }
    while (i <= m) tmp[k++] = a[i++];
    while (j <= r) tmp[k++] = a[j++];
    for (k = l; k <= r; k++) a[k] = tmp[k];
    return count;
}

int main() {
    int n;
    cin >> n;
    a.resize(n);
    tmp.resize(n);
    for (int &x : a) cin >> x;
    cout << countInversions(0, n - 1) << endl;
    return 0;
}

The result can be up to n(n−1)/2, so for n = 105 we use the type long long.

Practice tasks

Every task has an example, hints and a solution. The solutions have been checked on the examples from the text.

TASK 01Difficulty: Easy

The union of two sorted arrays

Two arrays sorted in ascending order are given (with no repetitions within the same array). Print all numbers that appear in at least one array, in ascending order and without repetitions.

Input: n, then n numbers; then m, then m numbers (1 ≤ n, m ≤ 105).

Example

Input

4
1 3 5 7
3
3 4 7

Output

1 3 4 5 7
TASK 02Difficulty: Medium

Sorting a large array

n integers are given (1 ≤ n ≤ 106). Print them sorted in descending order. An O(n²) algorithm is too slow here.

Example

Input

6
4 -1 7 4 0 10

Output

10 7 4 4 0 -1
Common mistakes and tips
  • The base case is l >= r; without it the recursion never stops.
  • Create the auxiliary array once (globally), not in every call – otherwise the program spends a lot of time creating arrays.
  • Do not forget to copy tmp[l..r] back into a after merging.
  • Store the number of inversions in a long long.

Check your knowledge

Open the quiz

Merge sort

1. How long does merging two sorted arrays of lengths n and m take?




2. What is the worst-case complexity of merge sort?




3. What is the drawback of merge sort compared to selection sort?




4. How many inversions does the array 3 1 2 have?