## CS 662: Theory of Parallel Algorithms Batcher's Sort

San Diego State University -- This page last updated March 27, 1995

8*8 Odd-Even Merging Circuit

## Translating Circuits to Code

Straighten out some wires
Makes the indexing easier

```8        merge      6    regroup      6         merge     4         merge     1
1                   1                   1                   1              2
5                   4           4                   5                   3
3                   3             3                   2              4
6                   8                 8                   6                   5
2                   2                   2                   3              6
4                   5           5                   8                   8
9                   9             9                   9              9

```

### Batcher's Merge-Exchange Sort

Input: N and array A[1:N] of items to sort

set T = ceiling(lg(N))
```for P = 2**(T-1), 2**(T-2), 2**(T-3), ..., 1 do

R = 0, D = P

for Q = 2**(T-1), 2**(T-2), 2**(T-3), ..., P do

for (K = 1 to N - D ) and  ((K-1) and P) = R do in parallel
if A[K] > A[K + D] then
swap(A[K], A[K + D ])
end if
end for

D = Q - P
R = P
end for
end for
```

(K + 1) and P means logical and of K and P

If number of processors is less than N than the swap becomes a merge