In this blog post I give an intuitive explanation of the Batcher odd-even mergesort algorithm. This sorting algorithm has the following properties:
- Constant execution time and memory access pattern, hence suitable for cryptographic purposes (modulo implementation-level auditing).
O(n log^2 n)time complexity andO(log^2 n)depth, which is a widely used practical bound for deterministic sorting networks. (AKS sorting networks are faster, but they are complex and not used in practice.)O(1)extra storage required beyond the inputs. This requires the implementation to be fully flattened. See below. Otherwise the algorithm still incurs a stack memory usage ofO(log n).
Almost all sorting networks are described as recursive algorithms. Sorting a two-element array is trivial: we compare the two elements and swap them if necessary. We assume this two-element sorting can be done in a way that does not leak any information about the elements. Otherwise, any algorithm built on top of these trivial steps will also leak some information about the elements, rendering the implementation unsuitable for cryptography.
Let us use void sort<k>(uint32_t input[1 << k]) with k >= 1 to denote the function that sorts 1 << k elements in place.
On most CPUs, specific instructions exist to compare and sort two elements in constant time.
On x86 one can use cmp and cmov. On AArch64, one can use cmp and csel.
If the platform cannot be determined, one can use a generic implementation:
/* Throughout this document we use a C-like pseudocode which uses various non-standard syntax,
* in particular C++-like template arguments.
*/
void sort<1>(uint32_t input[2]) {
uint32_t x = input[0];
uint32_t y = input[1];
uint32_t mask = -(x > y);
uint32_t diff = mask & (x ^ y);
input[0] = x ^ diff;
input[1] = y ^ diff;
}This assumes that x > y (which evaluates to either 0 or 1) will be translated into a constant-time instruction.
If even this cannot be determined, one uses bitwise operations to emulate x > y which can be rather slow.
For these reasons the platform-dependent inline assembly versions should be favored where possible.
Now suppose we have implemented sort<k>, we look at how to implement sort<k + 1>.
The basic idea of mergesort is:
void sort<k + 1>(uint32_t input[1 << (k + 1)]) {
sort<k>(input); // sort the first half
sort<k>(input + (1 << k)); // sort the second half
merge<k>(input, input + (1 << k)); // merge the two halves
}On line 4 we invoked void merge<k>(uint32_t input1[1 << k], uint32_t input2[1 << k]) which does the following:
it takes two input arrays of length 1 << k, such that both arrays are already sorted,
and combines the two halves into a single sorted array.
The combined array is written directly into the storage space of the input arrays,
by treating input1 as the first half of the output and input2 as the second half.
The difficulty lies in implementing this merge operation in constant-time and also in-place.
If we do not care too much about efficiency then merge<k> can be implemented as follows:
void merge<0>(uint32_t* input1, uint32_t* input2) { /* same as two element sort */ }
void merge<k + 1>(uint32_t input1[1 << (k + 1)], uint32_t input2[1 << (k + 1)]) {
merge<k>(input1, input2); // Merge first halves of input1 and input2
merge<k>(input1 + (1 << k), input2 + (1 << k)); // Merge second halves of input1 and input2
merge<k>(input1 + (1 << k), input2); // Merge middle two halves
}What's going on here? We now give a formal analysis of the merge algorithm above that will illustrate the style of reasoning
we will later apply to Batcher's sorting algorithm.
We use P, Q, R, ... to denote sorted arrays.
Below, we shall assume that all arrays denoted by single letters are all of the same length k.
If P, Q are sorted arrays of equal length, we use [P Q] to denote their concatenation (not necessarily sorted),
and we use M[P Q] to denote the result of merging P and Q (which produces a sorted array).
We now introduce a transitive relation on arrays.
We write P < Q if each element of P is less than or equal to every element of Q.
Note that P < P does not hold in general unless all elements in P are equal.
This is why we write it as P < Q rather than P <= Q to avoid suggestion of reflexivity.
We now make a few observations:
- Lemma 1: If
P < Q,Q < R, thenP < R. - Lemma 2: If
M[P Q] = [P' Q'], thenP' < Q'. - Lemma 3: If either
P < RorQ < Rholds, andM[P Q] = [P' Q'], thenP' < R. (Proof: There are at leastkelements in[P Q]that are less than or equal to all elements inR. SinceP'contains the smallestkelements in[P Q], they must all be less than or equal to all elements inR.) - Lemma 4: If either
R < PorR < Qholds, andM[P Q] = [P' Q'], thenR < Q'. (Proof: Symmetric to Lemma 3.) - Lemma 5: If both
P < RandQ < Rholds, andM[P Q] = [P' Q'], thenQ' < R. (Proof: All elements in [P Q] are less than or equal to every element ofR. Since elements inQ'are a subset of elements in[P Q], they must all be less than or equal to every element ofR.) - Lemma 6: If both
R < PandR < Qholds, andM[P Q] = [P' Q'], thenR < P'. (Proof: Symmetric to Lemma 5.)
Now assume input1 = [P1 P2] and input2 = [Q1 Q2].
Since both input1 and input2 are sorted, we have P1 < P2, Q1 < Q2.
Now suppose M[P1 Q1] = [P1' Q1'], M[P2 Q2] = [P2' Q2']. This corresponds to the first two steps of the merge algorithm above.
By Lemma 3, we have P1' < P2 and P1' < Q2. By Lemma 6, we have P1' < P2'.
Invoking Lemma 3 and Lemma 6 again, we get P1 < Q2', Q1 < Q2', hence Q1' < Q2'.
By Lemma 2 we also have P1' < Q1' and P2' < Q2'.
Hence P1' contains the k smallest elements in [input1 input2],
and P2' contains the k largest elements in [input1 input2].
Let M[P2' Q1'] = [P2'' Q1'']. This corresponds to the final step of the merge algorithm.
Then we have P1' < P2'' < Q1'' < Q2'. Hence [P1' P2'' Q1'' Q2'] is a fully sorted list.
What's the time complexity of our naive in-place mergesort algorithm?
The time complexity of merge satisfies the recursion T(n) = 3T(n/2), hence it is O(n^log_2(3)).
Then the time complexity of sort satisfies T(n) = 2T(n/2) + O(n^log_2(3)), so it is O(n^log_2(3)) as well.
This is not optimal, but it has the advantage of being easy to understand.
Batcher's odd-even mergesort is based an ingenious way of implementing merge.
Suppose P, Q are two arrays of length k, and k is even.
We introduce odd-even partitioning as follows.
We assume array indices start from 1. (This is not the norm in C/C++ but it makes referring to the "r-th element" easier.)
The odd-even partitioning of P is (P1, P2) with P1 containing P[1], P[3], ..., P[k - 1],
and P2 containing P[2], P[4], ..., P[k].
We similarly partition Q into (Q1, Q2).
Then P1, P2, Q1, Q2 each has length k/2. Assume that we have already implemented merge for arrays of length k/2.
Let M[P1 Q1] = [P1' Q1'], M[P2 Q2] = [P2' Q2'].
We then recombine (P1', P2') following the reverse of odd-even partitioning.
That is we define P' = [P1'[1], P2'[1], P1'[2], P2'[2], ..., P1'[k/2], P2'[k/2]].
Similarly we define Q' = [Q1'[1], Q2'[1], Q1'[2], Q2'[2], ..., Q1'[k/2], Q2'[k/2]].
Then a "miracle" happens: [P' Q'] is in an "almost-sorted" state.
Every element is displaced from its correctly sorted position by at most one position.
We now try to understand why this is the case.
We define a new notion of shifted comparisons over arrays.
If P, Q are two arrays of the same length, we write P <=(t) Q if the r-th element of P is always less than or
equal to the (r + t)-th element of Q, when both indices are within the length of P, Q.
One easily verifies the P <=(t) Q relation satisfies the following reflexivity and transitivity properties:
- If
Pis sorted thenP <=(t) Pfor any t. - If
P <=(t1) Q <=(t2) RthenP <=(t1 + t2) R.
Let the odd-even partitioning of P, Q be (P1, P2), (Q1, Q2) respectively.
Then we have P1 <=(0) P2 <=(1) P1, Q1 <=(0) Q2 <=(1) Q1.
Furthermore we have the following lemma:
- Lemma 7: If
P1 <=(t1) P2,Q1 <=(t2) Q2, thenM[P1 Q1] <=(t1 + t2) M[P2 Q2].
Proof: Suppose the r-th element of M[P2 Q2] is x. Then x is greater than or equal to r elements in [P2 Q2].
For each such element y except at most (t1 + t2) initial ones, there is a corresponding element z in [P1 Q1]
such that z <= y. Hence x is greater than or equal to at least (r - t1 - t2) elements in [P1 Q1]. Therefore, x
is greater than or equal to the (r - t1 - t2)-th element in M[P1 Q1].
Following Lemma 7, we get M[P1 Q1] <=(0) M[P2 Q2] <=(2) M[P1 Q1]. What does this give us?
The array recombined from M[P1 Q1], M[P2 Q2] has the form
M[P1 Q1][1], M[P2 Q2][1], M[P1 Q1][2], M[P2 Q2][2], M[P1 Q1][3], M[P2 Q2][3], ..., M[P1 Q1][k], M[P2 Q2][k]
One easily sees that M[P1 Q1][1] must be the smallest element in the entire array, and M[P2 Q2][k] must be the largest element.
Dropping these two extremes, we divide the remaining array into groups of two:
M[P1 Q1][1], M[P2 Q2][1], M[P1 Q1][2], M[P2 Q2][2], M[P1 Q1][3], M[P2 Q2][3], ..., M[P1 Q1][k], M[P2 Q2][k]
-------------------------|-------------------------|............
Group 1 Group 2
Group 1 = [M[P2 Q2][1], M[P1 Q1][2]]
Group 2 = [M[P2 Q2][2], M[P1 Q1][3]]
......
Since M[P1 Q1] and M[P2 Q2] are sorted, we have M[P1 Q1][2] <= M[P1 Q1][3] and M[P2 Q2][1] <= M[P2 Q2][2].
By M[P1 Q1] <=(0) M[P2 Q2] we have M[P1 Q1][2] <= M[P2 Q2][2].
By M[P2 Q2] <=(2) M[P1 Q1] we have M[P2 Q2][1] <= M[P1 Q1][3].
It follows that adjacent groups are already correctly sorted. We just need to sort each individual group.
In the literature, we say the recombined array is "almost-sorted".
But this is easy and can be done in linear time.
If we ignore the time needed for the odd-even partitioning operation,
this gives us a merge algorithm with time complexity T(n) = 2T(n/2) + O(n), hence O(n log_2 n).
The sort algorithm time complexity is T(n) = 2T(n/2) + O(n log_2 n), hence O(n log_2^2 n).
In the analysis above we ignored the time complexity of the odd-even partitioning operation.
If we do it naively we either introduce O(n) extra storage, or O(n log_2 n) extra time.
Fortunately, we do not need to carry out the partitioning operation physically at all.
We can simply find a formula for the list of indices that would be contained in each partition.
Suppose you want to merge two lists P, Q, each having length (1 << k).
Let us look at the partitions of P that would be accessed during the recursive process.
We execute the merge algorithm in k + 1 "levels".
At the i-th level (0 <= i <= k), P is partitioned into (1 << (k - i)) parts, each with length (1 << i).
For each number 1 <= j <= (1 << (k - i - 1)), the j-th part and the (j + (1 << (k - i - 1)))-th part of level i
form the odd-even partitioning of the j-th part of the (i + 1)-th level.
Let part_{i, j} be j-th part of the i-th level. Then it is defined by
part_{i, j}[r] = P[j + (r - 1) * (1 << (k - i))]
(1 <= j <= (1 << (k - i)), 1 <= r <= (1 << i))
Hence at level k there is only one partition, namely P itself.
The odd-even partitioning of P forms the two partitions at level k - 1, and so on.
Clearly part_{i, j} describes all partitions of P that would be accessed during merge.
By replacing P with Q in the above formula, it also describes all partitions of Q.
Now the algorithm can be described as follows:
/* -1 at the end to account for the fact that our indices start from 1. */
#define INPUT_PART_OFFSET(k, i, j, r) ((j) + ((r) - 1) * (1 << ((k) - (i))) - 1)
/* Prefer replacing this with architecture-specific inline assembly to ensure constant-time */
void compare_and_swap(uint32_t * input1, uint32_t * input2) {
uint32_t x = *input1;
uint32_t y = *input2;
uint32_t mask = -(x > y);
uint32_t diff = mask & (x ^ y);
*input1 = x ^ diff;
*input2 = y ^ diff;
}
/* Given two input arrays with length 1 << k and a part specification given by (level, part_idx),
* merge the two parts, writing the lower part into input1 and higher part into input2.
* 0 <= level <= k, 1 <= part_idx <= (1 << (k - level)).
* To merge whole arrays, call this function with level == k, part_idx == 1.
*/
void merge<k>(uint32_t input1[1 << k], uint32_t input2[1 << k], uint32_t level, uint32_t part_idx) {
if (level == 0) {
uint32_t offset = INPUT_PART_OFFSET(k, 0, part_idx, 1);
compare_and_swap(input1 + offset, input2 + offset);
return;
}
/* Merge P1 and Q1 */
merge<k>(input1, input2, level - 1, part_idx);
/* Merge P2 and Q2 */
merge<k>(input1, input2, level - 1, part_idx + (1 << (k - level)));
/* Linear time fixup */
for (uint32_t r = 2; r < (1 << level); r += 2) {
uint32_t offset1 = INPUT_PART_OFFSET(k, level, part_idx, r);
uint32_t offset2 = INPUT_PART_OFFSET(k, level, part_idx, r + 1);
compare_and_swap(input1 + offset1, input1 + offset2);
compare_and_swap(input2 + offset1, input2 + offset2);
}
uint32_t offset1 = INPUT_PART_OFFSET(k, level, part_idx, (1 << level));
uint32_t offset2 = INPUT_PART_OFFSET(k, level, part_idx, 1);
compare_and_swap(input1 + offset1, input2 + offset2);
}
void sort<k>(uint32_t input[1 << k]) {
if (k == 0) return;
sort<k - 1>(input);
sort<k - 1>(input + (1 << (k - 1)));
merge<k - 1>(input, input + (1 << (k - 1)), k - 1, 1);
}The partitioning scheme we derived above suggests the following kind of simplification: instead of sorting two halves of the input array, we directly sort the two partitions of the array. However we must then modify the fixup part of the merge algorithm. Otherwise we would be writing the lower part of the array into the odd partition and the higher part into the even partition. Fortunately, such a modification is not too difficult.
- Lemma 8: Let
Rbe an array of length(1 << k)with(k >= 2). Let the odd-even partitioning ofRbe(P, Q), and we assume bothP, Qare sorted. Let(P1, P2)and(Q1, Q2)be the odd-even partitionings ofP, Q. LetM[P1 Q1] = (P1', Q1'), that is, the odd partition ofM[P1 Q1]isP1', and the even partition ofM[P1 Q1]isQ1'. Similarly, letM[P2 Q2] = (P2', Q2'). If(P1', P2')is recombined intoP',(Q1', Q2')is recombined intoQ', and(P', Q')is recombined intoR', thenR'is almost-sorted.
Proof: By Lemma 7 we still have M[P1 Q1] <=(0) M[P2 Q2] <=(2) M[P1 Q1].
The r-th element of P1', Q1', P2', Q2' appear at positions 4r - 3, 4r - 2, 4r - 1, 4r in R' respectively.
Because P1', Q1' are the odd-even partitioning of M[P1 Q1], we have P1' <=(0) Q1' <=(1) P1'.
Similarly, we also have P2' <=(0) Q2' <=(1) P2'.
Also, by splitting M[P1 Q1] <=(0) M[P2 Q2] <=(2) M[P1 Q1] at odd and even indices we get
P1' <=(0) P2' <=(1) P1' and Q1' <=(0) Q2' <=(1) Q1'.
(Notice that the shift is halved from 2 to 1. Why halved? Because the r-th element of P2' is the (2r - 1)-th element of
M[P2 Q2], while the (r + 1)-th element of P1' is the (2r + 1)-th element of M[P1 Q1].)
Now for each r >= 1 we establish the following inequalities:
R'[4r - 2] <= R'[4r]: this follows fromQ1' <=(0) Q2'.R'[4r - 2] <= R'[4r + 1]: this follows fromQ1' <=(1) P1'.R'[4r - 1] <= R'[4r]: this follows fromP2' <=(0) Q2'.R'[4r - 1] <= R'[4r + 1]: this follows fromP2' <=(1) P1'.R'[4r] <= R'[4r + 2]: this follows fromQ2' <=(1) Q1'.R'[4r] <= R'[4r + 3]: this follows fromQ2' <=(1) P2'.R'[4r + 1] <= R'[4r + 2]: this follows fromP1' <=(0) Q1'.R'[4r + 1] <= R'[4r + 3]: this follows fromP1' <=(0) P2'.
Thus adjacent two-element groups in R' are still correctly sorted, so R' is almost-sorted.
This means we can implement merge in the following way:
/* Given an input array of length 1 << k and two part specifications (level, part_idx1) and (level, part_idx2),
* such that both parts are already sorted, merge the two parts and write the odd-partition of the merged sorted array
* into part_idx1, and the even-partition of the merged sorted array into part_idx2.
* Hence, if (level, part_idx1) and (level, part_idx2) are the odd-even partitioning of a larger part,
* then that part is also sorted.
*/
void merge<k>(uint32_t input[1 << k], uint32_t level, uint32_t part_idx1, uint32_t part_idx2) {
if (level == 0) {
uint32_t offset1 = INPUT_PART_OFFSET(k, 0, part_idx1, 1);
uint32_t offset2 = INPUT_PART_OFFSET(k, 0, part_idx2, 1);
compare_and_swap(input + offset1, input + offset2);
return;
}
/* Merge P1, Q1 */
merge<k>(input, level - 1, part_idx1, part_idx2);
/* Merge P2, Q2 */
merge<k>(input, level - 1, part_idx1 + (1 << (k - level)), part_idx2 + (1 << (k - level)));
/* Fixup */
/* Let R be the array obtained by recombining part_idx1 and part_idx2.
* Then the pairs to be fixed are (R[2], R[3]), (R[4], R[5]), ..., (R[(1 << (level + 1)) - 1], R[1 << (level + 1)]).
* They correspond to (part_idx2[1], part_idx1[2]), ..., (part_idx2[(1 << level) - 1], part_idx1[1 << level])
*/
for (uint32_t r = 1; r < (1 << level); r++) {
uint32_t offset1 = INPUT_PART_OFFSET(k, level, part_idx2, r);
uint32_t offset2 = INPUT_PART_OFFSET(k, level, part_idx1, r + 1);
compare_and_swap(input + offset1, input + offset2);
}
}The magical thing about this modified version is that, when we write down the sort function, the recursive sort calls disappear!
Why we don't need recursive sort calls? Because the merge calls at level (i - 1) already sorted the parts at level i.
void sort<k>(uint32_t input[1 << k]) {
for (uint32_t i = 1; i <= k; i++) {
/* Assume that all parts at level i - 1 are sorted. */
for (uint32_t j = 1; j <= (1 << (k - i)); j++) {
merge<k>(input, i - 1, j, j + (1 << (k - i)));
}
}
/* Voila! No recursive sort calls! */
}The above modified version already flattened the sort procedure.
We can also flatten the merge procedure so the entire algorithm does not use recursion at all.
To do so, we notice that the intermediate invocations of merge can be labeled with binary integers.
For example if you call merge with level = t then it makes two calls with level = t - 1, four calls with level = t - 2, etc.
Let us thus use (t - i)-bit numbers 0 <= w < (1 << (t - i)) to label calls at level i.
Thus call w at level i makes two level i - 1 calls with numbers w and w + (1 << (t - i)).
Then notice that the part_idx numbers at level i call number w can be computed as part_idx + (w << (k - t)).
This gives us the following flattened implementation:
void merge<k>(uint32_t input[1 << k], uint32_t level, uint32_t part_idx1, uint32_t part_idx2) {
/* Level 0 merge calls */
for (uint32_t w = 0; w < (1 << level); w++) {
uint32_t subcall_part_idx1 = part_idx1 + (w << (k - level));
uint32_t subcall_part_idx2 = part_idx2 + (w << (k - level));
uint32_t offset1 = INPUT_PART_OFFSET(k, 0, subcall_part_idx1, 1);
uint32_t offset2 = INPUT_PART_OFFSET(k, 0, subcall_part_idx2, 1);
compare_and_swap(input + offset1, input + offset2);
}
for (uint32_t i = 1; i <= level; i++) {
/* Assume that all level (i - 1) merge calls are already completed.
* Perform level i fixup.
*/
for (uint32_t w = 0; w < (1 << (level - i)); w++) {
uint32_t subcall_part_idx1 = part_idx1 + (w << (k - level));
uint32_t subcall_part_idx2 = part_idx2 + (w << (k - level));
for (uint32_t r = 1; r < (1 << i); r++) {
uint32_t offset1 = INPUT_PART_OFFSET(k, i, subcall_part_idx2, r);
uint32_t offset2 = INPUT_PART_OFFSET(k, i, subcall_part_idx1, r + 1);
compare_and_swap(input + offset1, input + offset2);
}
}
}
}To support non-power-of-two input sizes, we can pretend the array is padded with "infinite" entries that are
"larger" (to be sorted after than) than all elements in the array. This is equivalent to saying, whenever we make
a compare_and_swap call, if one of the offsets is beyond the input range then we do nothing.
Such comparisons depend only on the array length but not its content,
and so does not affect the "cryptographic constant-time" property of the algorithm.
Batcher's odd-even merging idea can be stated in a more general way as follows:
Let L be a list with an even number of elements.
We mark each position in L as either black or white.
We do not require the number of black and white positions to be equal.
It is sufficient that there are an even number of black positions,
and an even number of white positions.
Let us use P to denote the black positions, and Q to denote the white positions.
We may further divide P into its odd positions P1 and even positions P2.
Similarly, we divide Q into odd positions Q1 and even positions Q2.
Let O ("odd positions") denote the union of P1 and Q1.
Let E ("even positions") denote the union of P2 and Q2.
Then the first position of L must be in O since it is the first position in either P or Q.
The last position of L must be in E since it is the last position in either P or Q.
Within this setting we state the following lemma:
- Lemma 9: Suppose that both the
Psublist and theQsublist ofLare sorted. If we now sort theOsublist intoO'(soO' = M[P1 Q1]), and writeO'back into the O-positions, and also sort theEsublist intoE'(soE' = M[P2 Q2]), and writeE'back into the E-positions, thenLis almost-sorted.
Proof: We first make a few observations:
- If
tis ther-th O-position, then there are at least(r - 2)and at most(r - 1)E-positions before it. (WLOG, assumetis inP1. Then there areuP1-positions andvQ1-positions before it, withu + v = r - 1. Then there must beuP2-positions before it. The number of Q2-positions before it is eithervorv - 1.) - If
tis ther-th E-position, then there are at leastrand at most(r + 1)O-positions before it. (Symmetric to above.) - In the two-element grouping of
L, every group must contain exactly one O-position and one E-position. (The first position ofLis an O-position and does not belong to any group. Thus the first group cannot be OO or EE, otherwise we violate the number relations. Suppose the firstigroups are all either OE or EO. Then before the(i + 1)-th group there are exactly2i + 1O-positions and2iE-positions. Then it is easy to see the(i + 1)-th group cannot be OO or EE either.)
Now consider two adjacent groups. By the above observations, they must be one of the following forms:
(O[2i + 2], E[2i + 1]), (O[2i + 3], E[2i + 2])
(O[2i + 2], E[2i + 1]), (E[2i + 2], O[2i + 3])
(E[2i + 1], O[2i + 2]), (O[2i + 3], E[2i + 2])
(E[2i + 1], O[2i + 2]), (E[2i + 2], O[2i + 3])
By Lemma 7, we have O' <=(0) E' <=(2) O'.
Then it is easy to verify, in all the above cases the two adjacent groups must have been correctly sorted.
If we combine our sort and merge functions, it would be as follows:
#define INPUT_PART_OFFSET(k, i, j, r) ((j) + ((r) - 1) * (1 << ((k) - (i))) - 1)
void sort<k>(uint32_t input[1 << k]) {
for (uint32_t i = 1; i <= k; i++) {
for (uint32_t j = 1; j <= (1 << (k - i)); j++) {
uint32_t level = i - 1;
uint32_t part_idx1 = j;
uint32_t part_idx2 = j + (1 << (k - i));
/* We shall call this loop the "t = 0" iteration */
for (uint32_t w = 0; w < (1 << level); w++) {
uint32_t subcall_part_idx1 = part_idx1 + (w << (k - level));
uint32_t subcall_part_idx2 = part_idx2 + (w << (k - level));
uint32_t offset1 = INPUT_PART_OFFSET(k, 0, subcall_part_idx1, 1);
uint32_t offset2 = INPUT_PART_OFFSET(k, 0, subcall_part_idx2, 1);
compare_and_swap(input + offset1, input + offset2);
}
for (uint32_t t = 1; t <= level; t++) {
for (uint32_t w = 0; w < (1 << (level - t)); w++) {
uint32_t subcall_part_idx1 = part_idx1 + (w << (k - level));
uint32_t subcall_part_idx2 = part_idx2 + (w << (k - level));
for (uint32_t r = 1; r < (1 << t); r++) {
uint32_t offset1 = INPUT_PART_OFFSET(k, t, subcall_part_idx2, r);
uint32_t offset2 = INPUT_PART_OFFSET(k, t, subcall_part_idx1, r + 1);
compare_and_swap(input + offset1, input + offset2);
}
}
}
}
}
}This function is not yet in a satisfactory shape: it has five layers of loops, which can introduce a significant amount of control-flow overhead. Furthermore, if the input size is not a power-of-two, we want to know exactly which parts of the loop can be skipped altogether, instead of relying on index bound checks. Therefore, we now consider how to simplify this program.
We first realize that within each iteration of i, each iteration of j can be executed in parallel,
since they operate on different parts of input.
Also, within each iteration of (i, j, t), each iteration of (w, r) can be executed in parallel.
Therefore, the idea is to use i and t as the outer loop variables, and merge loop structures on j, w, r.
If we expand out the index calculations in the algorithm, we see that:
In the t = 0 iteration:
subcall_part_idx1 = j + (w << (k + 1 - i))
subcall_part_idx2 = j + (1 << (k - i)) + (w << (k + 1 - i))
offset1 = j + (w << (k + 1 - i)) - 1
offset2 = j + (1 << (k - i)) + (w << (k + 1 - i)) - 1
Since j iterates over 1 <= j <= (1 << (k - i)), and w iterates over 0 <= w < (1 << (i - 1)),
we see that j + (w << (k + 1 - i)) - 1 iterates over every number x with 0 <= x < (1 << k) and x & (1 << (k - i)) = 0.
We can represent every such offset1 value with a number u with 0 <= u < (1 << (k - 1)):
mask1 = (1 << (k - i)) - 1
mask2 = ((1 << (i - 1)) - 1) << (k - i)
offset1 = (u & mask1) | ((u & mask2) << 1)
offset2 = offset1 + (1 << (k - i))
If the input size is not a power of two, we stop at the first u value such that offset2 >= len.
In the 1 <= t <= level iterations:
subcall_part_idx1 = j + (w << (k + 1 - i))
subcall_part_idx2 = j + (1 << (k - i)) + (w << (k + 1 - i))
offset1 = subcall_part_idx2 + (r - 1) * (1 << (k - t)) - 1
= j + (1 << (k - i)) + (w << (k + 1 - i)) + ((r - 1) << (k - t)) - 1
offset2 = subcall_part_idx1 + r * (1 << (k - t)) - 1
= j + (w << (k + 1 - i)) + (r << (k - t)) - 1
= offset1 - (1 << (k - i)) + (1 << (k - t))
Since t < i, we have k - t > k - i, and we see that offset1 < offset2.
Now j iterates over 1 <= j <= (1 << (k - i)), w iterates over 0 <= w < (1 << (i - 1 - t)),
and r iterates over 1 <= r < (1 << t).
We see that j + (w << (k + 1 - i)) + (r << (k - t)) - 1 iterates over
every number x with (1 << (k - t)) <= x < (1 << k) and x & (1 << (k - i)) = 0.
We can represent every such offset2 value with a number u with (1 << (k - t - 1)) <= u < (1 << (k - 1)):
mask1 = (1 << (k - i)) - 1
mask2 = ((1 << (i - 1)) - 1) << (k - i)
offset2 = (u & mask1) | ((u & mask2) << 1)
offset1 = offset2 + (1 << (k - i)) - (1 << (k - t))
Again, if the input size is not a power of two, we stop at the first u value such that offset2 >= len.
This leads to the following simplified sort algorithm:
void sort<k>(uint32_t input[1 << k]) {
for (uint32_t i = 1; i <= k; i++) {
const uint32_t mask1 = (1 << (k - i)) - 1;
const uint32_t mask2 = ((1 << (i - 1)) - 1) << (k - i);
/* t = 0 iterations */
for (uint32_t u = 0; u < (1 << (k - 1)); u++) {
uint32_t offset1 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset2 = offset1 + (1 << (k - i));
compare_and_swap(input + offset1, input + offset2);
}
/* 1 <= t <= i - 1 iterations */
for (uint32_t t = 1; t < i; t++) {
for (uint32_t u = (1 << (k - t - 1)); u < (1 << (k - 1)); u++) {
uint32_t offset2 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset1 = offset2 + (1 << (k - i)) - (1 << (k - t));
compare_and_swap(input + offset1, input + offset2);
}
}
}
}When the input length is not a power of two, we stop the inner-most loop as soon as offset2 >= len.
void sort<k, len>(uint32_t input[len]) {
/* Assume len <= (1 << k) */
for (uint32_t i = 1; i <= k; i++) {
const uint32_t mask1 = (1 << (k - i)) - 1;
const uint32_t mask2 = ((1 << (i - 1)) - 1) << (k - i);
for (uint32_t u = 0; u < (1 << (k - 1)); u++) {
uint32_t offset1 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset2 = offset1 + (1 << (k - i));
if (offset2 >= len) break;
compare_and_swap(input + offset1, input + offset2);
}
for (uint32_t t = 1; t < i; t++) {
for (uint32_t u = (1 << (k - t - 1)); u < (1 << (k - 1)); u++) {
uint32_t offset2 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset1 = offset2 + (1 << (k - i)) - (1 << (k - t));
if (offset2 >= len) break;
compare_and_swap(input + offset1, input + offset2);
}
}
}
}Now we notice that in each loop over u there are two bound checks u < (1 << (k - 1)) and offset2 >= len.
We can actually merge the two checks, by adding a single high bit to mask2:
void sort<k, len>(uint32_t input[len]) {
for (uint32_t i = 1; i <= k; i++) {
const uint32_t mask1 = (1 << (k - i)) - 1;
const uint32_t mask2 = ((1 << i) - 1) << (k - i); /* Add one high bit! */
for (uint32_t u = 0; /* TRUE */; u++) {
uint32_t offset1 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset2 = offset1 + (1 << (k - i));
if (offset2 >= len) break;
compare_and_swap(input + offset1, input + offset2);
}
for (uint32_t t = 1; t < i; t++) {
for (uint32_t u = (1 << (k - t - 1)); /* TRUE */; u++) {
uint32_t offset2 = (u & mask1) | ((u & mask2) << 1);
uint32_t offset1 = offset2 + (1 << (k - i)) - (1 << (k - t));
if (offset2 >= len) break;
compare_and_swap(input + offset1, input + offset2);
}
}
}
}Why add one leading bit? If u < (1 << (k - 1)) then we see that
the extra one bit has no effect in computing offset1 and offset2.
However, as soon as u == (1 << (k - 1)) we see that (u & mask1) | ((u & mask2) << 1) == (1 << k),
so we must have offset2 >= (1 << k) >= len, and the loop will stop.