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 , because the final merge is a serial loop over all 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 and span .
Spawning the halves is not enough
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 sortThe work is that of ordinary merge sort (Merge Sort), . The two calls run in parallel, but the merge follows them in series and takes time on its own:
The parallelism is : 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 .
Merging by divide and conquer
To merge two sorted arrays and in parallel, split the problem into two independent smaller merges:
- Let be the longer array (swap if needed) and let be its median, at index .
- Binary-search for the position where would be inserted: .
- Then belongs at position of the output. Everything in and goes before it and everything else after it.
- 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.
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 syncThe program below traces the first two levels of the recursion on two sorted lists and checks the result.
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 with , so . Each recursive merge gets at most half of and possibly all of , so at most
elements. The binary search costs and the two recursive calls run in parallel, so
because the recursion has levels, each adding . For the work, the split is uneven: with (the median element itself is output, so the sizes sum to ). The recursion tree has fewer than internal nodes, each costing , which gives at once; the substitution method (The Substitution Method) with the guess proves the tight bound . 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 ) gives
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.
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 ; with the parallel merge it grows almost linearly, about 3 times per quadrupling of in this range (the 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 , and random inputs do reach it.
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.
#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?
In the parallel merge, why does each recursive call get at most elements?
- Because the median of the longer array splits it in half and the longer array has at least elements
- Because binary search always finds the middle of the shorter array
- Because both arrays are split in half
- Because the arrays have equal length
What is the span of the parallel merge on elements?
Why can the two recursive merges run in parallel without a race?
- They read different arrays
- They write disjoint ranges of the output, fixed by the position of the median
- They are protected by a lock
- Only one of them writes