function oddEvenSort(array: number[]) {let sorted = false;
while (!sorted) {sorted = true;
for (let i = 1; i + 1 < array.length; i += 2) { if (array[i] > array[i + 1]) { swap(array, i, i + 1); sorted = false; }}
for (let i = 0; i + 1 < array.length; i += 2) { if (array[i] > array[i + 1]) { swap(array, i, i + 1); sorted = false; }}
}
}
Start. Each round has two phases: odd pairs (1-2, 3-4, …) then even pairs (0-1, 2-3, …); every pair in a phase is independent.
Understanding Odd-even sort
The idea
Odd-even transposition sort compares the pairs (1, 2), (3, 4), (5, 6), … in one phase and the pairs (0, 1), (2, 3), (4, 5), … in the next, swapping each pair that is out of order. No two pairs in a phase share an element, so every comparison of a phase can happen at the same time.
On one processor it is just bubble sort with a stranger order, and it does the same O(n²) work. On n/2 processors, one per pair, each phase costs one step and the whole sort finishes in n rounds: that is what it was designed for, and why it appears in sorting networks and GPU code.
The four stages
Complexity
Versus its siblings
Pseudocode
ODDEVENSORT(array)
repeat until a round swaps nothing
odd phase: for every pair (1, 2), (3, 4), … in parallel: swap if out of order
even phase: for every pair (0, 1), (2, 3), … in parallel: swap if out of order
When to use
Pitfalls
History
Nico Habermann described the parallel neighbour sort in 1972 for arrays of processors. It is the simplest sorting network, and the proof that n rounds always suffice, by the 0-1 principle, is a classic exercise in parallel algorithms courses.