Skip to main content
2 of 3
added 142 characters in body
Justin
  • 21.3k
  • 1
  • 21
  • 36

Find the optimal sorting network

Sorting networks are an abstract model of "wires" carrying numbers, which outputs them sorted.

A comparator in a sorting network works as follows:

https://en.wikipedia.org/wiki/File:Sorting-network-comparator-demonstration.svg

This is the optimal sorting network for 4 numbers:

https://en.wikipedia.org/wiki/File:SimpleSortingNetworkFullOperation.svg

Since there are two kinds of "optimal" sorting networks people care about, we are going for the least number of comparators (those vertical lines).


Given an integer n, output a list of comparators which designates an optimal sorting network for n inputs. The "comparators" are a pair of indices which say which indices in the working array to compare / swap. The indices must be 0-based.

So for the example sorting network, this would be a valid output (viewing 0 as the top wire):

(0, 2), (1, 3), (0, 1), (2, 3), (1, 2)

As would this:

(0, 2), (1, 3), (2, 3), (0, 1), (1, 2)

Additionally, any whitespace is ignored (except for tokenizing), and any non-digit is considered whitespace, so this is also a valid output:

0 2 1 3 2 3 0 1 1 2

And also:

(0, 2)
(1
 3)
((2, 3, 0), 1)
(1, 2)

Furthermore, functions may simply return some iterable that - when flattened - gives the list of numbers in the correct order.

Justin
  • 21.3k
  • 1
  • 21
  • 36