TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Parallel Merge Sort with a Parallel Merge

Parallel Merge Sort with a Parallel Merge

Merge sort looks made for parallelism: its two recursive calls work on disjoint halves, so they can simply be spawned. Doing only that, though, gives a disappointing parallelism of Θ(lg⁡n)\Theta(\lg n), because the final merge is a serial loop over all nn elements. This lesson finds the bottleneck with the work and span measures, removes it with a divide-and-conquer parallel merge, and arrives at a sort with work Θ(nlg⁡n)\Theta(n \lg n) and span Θ(lg⁡3n)\Theta(\lg^3 n).

Spawning the halves is not enough

text
MERGE-SORT-SPAWN(A, lo, hi)         // sort A[lo .. hi - 1]
1  if hi - lo <= 1
2      return
3  mid = floor((lo + hi) / 2)
4  spawn MERGE-SORT-SPAWN(A, lo, mid)
5  MERGE-SORT-SPAWN(A, mid, hi)
6  sync
7  MERGE(A, lo, mid, hi)             // the serial merge of merge sort

The work is that of ordinary merge sort (Merge Sort), T1(n)=2T1(n/2)+Θ(n)=Θ(nlg⁡n)T_1(n) = 2T_1(n/2) + \Theta(n) = \Theta(n \lg n). The two calls run in parallel, but the merge follows them in series and takes Θ(n)\Theta(n) time on its own:

T∞(n)=T∞(n/2)+Θ(n)=Θ(n).T_\infty(n) = T_\infty(n/2) + \Theta(n) = \Theta(n).

The parallelism is Θ(nlg⁡n)/Θ(n)=Θ(lg⁡n)\Theta(n \lg n)/\Theta(n) = \Theta(\lg n): about 20 for a million elements, however many processors are available. The serial merge at the top of the recursion is a critical path of length nn.

Merging by divide and conquer

To merge two sorted arrays XX and YY in parallel, split the problem into two independent smaller merges:

  1. Let XX be the longer array (swap if needed) and let xx be its median, at index q1=⌊∣X∣/2⌋q_1 = \lfloor \lvert X \rvert / 2 \rfloor.
  2. Binary-search YY for the position q2q_2 where xx would be inserted: Y[0..q2−1]<x≤Y[q2..]Y[0..q_2-1] < x \le Y[q_2..].
  3. Then xx belongs at position q1+q2q_1 + q_2 of the output. Everything in X[0..q1−1]X[0..q_1-1] and Y[0..q2−1]Y[0..q_2-1] goes before it and everything else after it.
  4. Merge the two "before" parts and the two "after" parts recursively, in parallel: they write disjoint parts of the output, so there is no race.
text
P-MERGE(X, Y, Z, out)            // merge sorted X and Y into Z[out ..]
1  if |X| < |Y|
2      swap X and Y
3  if |X| == 0
4      return                     // both are empty
5  q1 = floor(|X| / 2)
6  q2 = number of elements of Y smaller than X[q1]     // binary search
7  Z[out + q1 + q2] = X[q1]
8  spawn P-MERGE(X[0 .. q1 - 1], Y[0 .. q2 - 1], Z, out)
9  P-MERGE(X[q1 + 1 ..], Y[q2 ..], Z, out + q1 + q2 + 1)
10 sync

The program below traces the first two levels of the recursion on two sorted lists and checks the result.

python · try it yourself
from bisect import bisect_left

def p_merge(X, Y, Z, out, depth=0, trace=None):
    if len(X) < len(Y):
        X, Y = Y, X
    if not X:
        return
    q1 = len(X) // 2
    q2 = bisect_left(Y, X[q1])
    if trace is not None and depth < 2:
        trace.append(f"{'  ' * depth}merge {X} with {Y}: median {X[q1]} goes to Z[{out + q1 + q2}]")
    Z[out + q1 + q2] = X[q1]
    p_merge(X[:q1], Y[:q2], Z, out, depth + 1, trace)                 # spawn
    p_merge(X[q1 + 1:], Y[q2:], Z, out + q1 + q2 + 1, depth + 1, trace)

X, Y = [2, 5, 7, 11, 13, 20, 24], [1, 6, 8, 9, 30]
Z, trace = [None] * (len(X) + len(Y)), []
p_merge(X, Y, Z, 0, trace=trace)
print("\n".join(trace))
print("Z =", Z, "sorted:", Z == sorted(X + Y))
merge [2, 5, 7, 11, 13, 20, 24] with [1, 6, 8, 9, 30]: median 11 goes to Z[7]
  merge [1, 6, 8, 9] with [2, 5, 7]: median 8 goes to Z[5]
  merge [13, 20, 24] with [30]: median 20 goes to Z[9]
Z = [1, 2, 5, 6, 7, 8, 9, 11, 13, 20, 24, 30] sorted: True

Why the subproblems shrink

Let n=∣X∣+∣Y∣n = \lvert X \rvert + \lvert Y \rvert with ∣X∣≥∣Y∣\lvert X \rvert \ge \lvert Y \rvert, so ∣X∣≥n/2\lvert X \rvert \ge n/2. Each recursive merge gets at most half of XX and possibly all of YY, so at most

∣X∣2+∣Y∣=n−∣X∣2≤n−n4=3n4\frac{\lvert X \rvert}{2} + \lvert Y \rvert = n - \frac{\lvert X \rvert}{2} \le n - \frac{n}{4} = \frac{3n}{4}

elements. The binary search costs Θ(lg⁡n)\Theta(\lg n) and the two recursive calls run in parallel, so

T∞merge(n)≤T∞merge(3n/4)+Θ(lg⁡n)=Θ(lg⁡2n),T_\infty^{\text{merge}}(n) \le T_\infty^{\text{merge}}(3n/4) + \Theta(\lg n) = \Theta(\lg^2 n),

because the recursion has Θ(lg⁡n)\Theta(\lg n) levels, each adding O(lg⁡n)O(\lg n). For the work, the split is uneven: W(n)=W(αn)+W((1−α)n)+Θ(lg⁡n)W(n) = W(\alpha n) + W((1 - \alpha)n) + \Theta(\lg n) with 1/4≤α≤3/41/4 \le \alpha \le 3/4 (the median element itself is output, so the sizes sum to n−1n - 1). The recursion tree has fewer than nn internal nodes, each costing O(lg⁡n)O(\lg n), which gives O(nlg⁡n)O(n \lg n) at once; the substitution method (The Substitution Method) with the guess W(n)≤c1n−c2lg⁡nW(n) \le c_1 n - c_2 \lg n proves the tight bound W(n)=Θ(n)W(n) = \Theta(n). So the parallel merge does linear work, like the serial one, but with polylogarithmic span.

The full sort

Replacing the serial merge by P-MERGE (into a temporary array, then copied back, which is a parallel loop of span Θ(lg⁡n)\Theta(\lg n)) gives

T1(n)=2T1(n/2)+Θ(n)=Θ(nlg⁡n),T∞(n)=T∞(n/2)+Θ(lg⁡2n)=Θ(lg⁡3n),T1T∞=Θ ⁣(nlg⁡2n).\begin{aligned} T_1(n) &= 2T_1(n/2) + \Theta(n) = \Theta(n \lg n), \\ T_\infty(n) &= T_\infty(n/2) + \Theta(\lg^2 n) = \Theta(\lg^3 n), \\ \frac{T_1}{T_\infty} &= \Theta\!\left(\frac{n}{\lg^2 n}\right). \end{aligned}

The program measures work and span exactly for both versions, counting one step per strand plus one per binary-search comparison and per element merged serially. It also confirms that each run sorts correctly.

python · try it yourself
import random

def search_cost(m):                     # comparisons of a binary search in m elements
    return max(1, m.bit_length())

def p_merge_ws(X, Y):
    """work and span of P-MERGE on sorted lists X, Y; also returns the merged list"""
    if len(X) < len(Y):
        X, Y = Y, X
    if not X:
        return 1, 1, []
    q1 = len(X) // 2
    lo, hi = 0, len(Y)
    while lo < hi:                       # binary search: first Y[q2] >= X[q1]
        mid = (lo + hi) // 2
        if Y[mid] < X[q1]: lo = mid + 1
        else: hi = mid
    q2 = lo
    w1, s1, left = p_merge_ws(X[:q1], Y[:q2])
    w2, s2, right = p_merge_ws(X[q1 + 1:], Y[q2:])
    c = 1 + search_cost(len(Y))
    return c + w1 + w2, c + max(s1, s2), left + [X[q1]] + right

def sort_ws(A, parallel_merge):
    if len(A) <= 1:
        return 1, 1, A
    mid = len(A) // 2
    w1, s1, L = sort_ws(A[:mid], parallel_merge)
    w2, s2, R = sort_ws(A[mid:], parallel_merge)
    if parallel_merge:
        wm, sm, M = p_merge_ws(L, R)
        wm, sm = wm + len(A), sm + search_cost(len(A))     # copy back with a parallel loop
    else:
        M = sorted(L + R)                                   # stands for the serial merge
        wm = sm = len(A)
    return 1 + w1 + w2 + wm, 1 + max(s1, s2) + sm, M

rng = random.Random(3)
print("     n   serial merge: work   span  par.  |  parallel merge: work   span   par.  sorted")
for n in [64, 256, 1024, 4096]:
    A = [rng.randint(0, 10**6) for _ in range(n)]
    wa, sa, Ma = sort_ws(A, False)
    wb, sb, Mb = sort_ws(A, True)
    print(f"{n:6} {wa:19} {sa:6} {wa / sa:5.0f}  | {wb:19} {sb:6} {wb / sb:6.0f}  {Ma == Mb == sorted(A)}")
     n   serial merge: work   span  par.  |  parallel merge: work   span   par.  sorted
    64                 511    133     4  |                1860    138     13  True
   256                2559    519     5  |                9787    251     39  True
  1024               12287   2057     6  |               48593    412    118  True
  4096               57343   8203     7  |              232175    618    376  True

With the serial merge the parallelism creeps up like lg⁡n\lg n; with the parallel merge it grows almost linearly, about 3 times per quadrupling of nn in this range (the lg⁡2n\lg^2 n in the denominator costs a little each time). The price is a constant factor of extra work: binary searches and the copy back.

The constant fractions are real, not just a worst-case artifact. The next program merges random sorted lists and records the largest share of the input that any recursive call receives; it never exceeds 3/43/4, and random inputs do reach it.

python · try it yourself
import random
from bisect import bisect_left

worst = 0.0
def p_merge(X, Y):
    global worst
    if len(X) < len(Y):
        X, Y = Y, X
    if not X:
        return []
    n = len(X) + len(Y)
    q1 = len(X) // 2
    q2 = bisect_left(Y, X[q1])
    if n >= 8:
        worst = max(worst, (q1 + q2) / n, (n - q1 - q2 - 1) / n)
    return p_merge(X[:q1], Y[:q2]) + [X[q1]] + p_merge(X[q1 + 1:], Y[q2:])

rng = random.Random(11)
for trial in range(200):
    a = sorted(rng.sample(range(10**5), rng.randint(1, 300)))
    b = sorted(rng.sample(range(10**5), rng.randint(1, 300)))
    assert p_merge(a, b) == sorted(a + b)
print(f"200 random merges correct; largest subproblem share {worst:.3f} (bound 0.75)")
200 random merges correct; largest subproblem share 0.750 (bound 0.75)

In C++

The parallel merge sort in C++, with the merge recursion written on index ranges into a temporary buffer, and work and span counted exactly as in the Python version. Each run is checked against std::is_sorted.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <random>
#include <utility>
#include <vector>
using std::vector;
using WS = std::pair<long long, long long>;           // (work, span)

long long search_cost(long long m) { long long c = 0; while (m) { c++; m >>= 1; } return std::max(1LL, c); }

// merge sorted a[x0..x1) and a[y0..y1) into t[out..]
WS p_merge(const vector<int>& a, int x0, int x1, int y0, int y1, vector<int>& t, int out) {
    if (x1 - x0 < y1 - y0) { std::swap(x0, y0); std::swap(x1, y1); }
    if (x1 == x0) return {1, 1};
    int q1 = x0 + (x1 - x0) / 2;
    int q2 = int(std::lower_bound(a.begin() + y0, a.begin() + y1, a[q1]) - a.begin());
    int pos = out + (q1 - x0) + (q2 - y0);
    t[pos] = a[q1];
    WS l = p_merge(a, x0, q1, y0, q2, t, out);          // spawned
    WS r = p_merge(a, q1 + 1, x1, q2, y1, t, pos + 1);
    long long c = 1 + search_cost(y1 - y0);
    return {c + l.first + r.first, c + std::max(l.second, r.second)};
}

WS p_sort(vector<int>& a, int lo, int hi, vector<int>& t) {
    if (hi - lo <= 1) return {1, 1};
    int mid = (lo + hi) / 2;
    WS l = p_sort(a, lo, mid, t), r = p_sort(a, mid, hi, t);   // in parallel
    WS m = p_merge(a, lo, mid, mid, hi, t, lo);
    std::copy(t.begin() + lo, t.begin() + hi, a.begin() + lo);  // a parallel loop
    m.first += hi - lo; m.second += search_cost(hi - lo);
    return {1 + l.first + r.first + m.first, 1 + std::max(l.second, r.second) + m.second};
}

int main() {
    std::mt19937 rng(3);
    std::printf("      n        work   span   parallelism  sorted\n");
    for (int n : {1024, 16384, 262144}) {
        vector<int> a(n), t(n);
        for (int& x : a) x = int(rng() % 1000000);
        WS ws = p_sort(a, 0, n, t);
        std::printf("%7d %11lld %6lld %13.0f  %s\n", n, ws.first, ws.second,
                    (double)ws.first / ws.second, std::is_sorted(a.begin(), a.end()) ? "yes" : "no");
    }
}
      n        work   span   parallelism  sorted
   1024       48590    412           118  yes
  16384     1080181    901          1199  yes
 262144    22126938   1658         13346  yes

At a quarter of a million elements the span is under 1700 steps against 22 million steps of work. Library sorts with parallel execution policies, such as std::sort(std::execution::par, ...), use related ideas (often a parallel merge or a sample-based partition) with coarse serial base cases.

Test yourself

What is the parallelism of merge sort that spawns its two halves but merges serially?

  1. Θ(1)\Theta(1)
  2. Θ(lg⁡n)\Theta(\lg n)
  3. Θ(n/lg⁡n)\Theta(n / \lg n)
  4. Θ(n)\Theta(n)

In the parallel merge, why does each recursive call get at most 3n/43n/4 elements?

  1. Because the median of the longer array splits it in half and the longer array has at least n/2n/2 elements
  2. Because binary search always finds the middle of the shorter array
  3. Because both arrays are split in half
  4. Because the arrays have equal length

What is the span of the parallel merge on nn elements?

  1. Θ(lg⁡n)\Theta(\lg n)
  2. Θ(lg⁡2n)\Theta(\lg^2 n)
  3. Θ(n)\Theta(\sqrt{n})
  4. Θ(n)\Theta(n)

Why can the two recursive merges run in parallel without a race?

  1. They read different arrays
  2. They write disjoint ranges of the output, fixed by the position of the median
  3. They are protected by a lock
  4. Only one of them writes