Pairwise Sorting Network

The Pairwise Sorting Network is an $$O(n \log^2 n)$$ sorting network. It is highly related to Odd-Even Merge Sort, so much so that it has the exact same comparators, just reordered.

Algorithm
The algorithm works as follows:


 * 1) Compare and swap each pair of the list.
 * 2) Recursively sort the odd and even elements in the list.
 * 3) Use a special network to sort the pairs.

Pseudocode
Iterative version.

procedure pairwise_sort(arr) do int a = 1 int n = length(arr) while a < n do int b = a      int c = 0 while b < n do compare and swap arr[b - a] and arr[b] b ++ c ++; if c >= a do c = 0 b += a;         end if end while a *= 2 end while a = floor(a / 4) int e = 1 while a > 0 do int d = e      while d > 0 do int b = (d + 1) * a         int c = 0 while b < n do compare and swap arr[b - d * a] and arr[b] c ++ b ++ if c >= a do c = 0 b += a            end if end while d = floor(d / 2) end while a = floor(a / 2) e = 2 * e + 1 end while end