import Mathlib /-! # Sorting networks with few comparators: 16 inputs (record challenge, minimize) A *comparator network* on `n` wires is a finite sequence of comparators `(i, j)` with `i < j`; the comparator `(i, j)` replaces the values `(xᵢ, xⱼ)` on wires `i`, `j` by `(min xᵢ xⱼ, max xᵢ xⱼ)`. It is a *sorting network* if for every input (from any linear order) the output is sorted: non-decreasing from wire `0` to wire `n - 1`. Its *size* is the number of comparators. Task: give a sorting network on 16 inputs with as few comparators as possible. The score is its size (length of the list; repeated comparators count). Correctness is stated for all linear orders (the original property), not through the 0-1 principle; `Tests.lean` proves the 0-1 principle and a kernel-checkable criterion. *References:* - [Knu98] D. E. Knuth, *The Art of Computer Programming, Vol. 3: Sorting and Searching*, 2nd ed., Addison-Wesley, 1998, §5.3.4. - [Dob] B. Dobbelaere, *Smallest and fastest sorting networks for a given number of inputs*, (consulted 2026-11-26, page dated 2026-11-20): best known size for 16 inputs is 60 (network found by SorterHunter, ); not known to be optimal. - [Har20] J. Harder, *An answer to the Bose-Nelson sorting problem for 11 and 12 channels*, arXiv:2012.04400: sizes 35 and 39 are optimal for 11 and 12 inputs; the optimal size is open for every `n ≥ 13`. -/ namespace SortingNetworkSize16 /-- Applying the comparator `c = (i, j)` to `v`: wire `i` receives `min (v i) (v j)` and wire `j` receives `max (v i) (v j)`; the other wires are unchanged ([Knu98, §5.3.4]; with `i < j` this is the standard comparator, which puts the smaller value on the lower wire). -/ def applyComparator {α : Type} [LinearOrder α] {n : ℕ} (v : Fin n → α) (c : Fin n × Fin n) : Fin n → α := fun k => if k = c.1 then min (v c.1) (v c.2) else if k = c.2 then max (v c.1) (v c.2) else v k /-- Running a comparator network (a list of comparators, applied from left to right). -/ def runNetwork {α : Type} [LinearOrder α] {n : ℕ} (net : List (Fin n × Fin n)) (v : Fin n → α) : Fin n → α := net.foldl applyComparator v /-- `net` is a (standard) sorting network on `n` wires: every comparator `(i, j)` has `i < j`, and for every linearly ordered type `α` and every input `v : Fin n → α` the output is sorted, i.e. monotone in the wire index ([Knu98, §5.3.4]). -/ def IsSortingNetwork {n : ℕ} (net : List (Fin n × Fin n)) : Prop := (∀ c ∈ net, c.1 < c.2) ∧ ∀ (α : Type) [LinearOrder α] (v : Fin n → α), Monotone (runNetwork net v) /-- The solver's construction: a comparator network on 16 wires. This definition is the hole to fill. -/ def answerNetwork : List (Fin 16 × Fin 16) := sorry /-- `answerNetwork` sorts every input. -/ theorem correct : IsSortingNetwork answerNetwork := sorry /-- The score: replace the hole by a natural-number literal `N` and prove `size ≤ N`. Lower is better (best known: 60). -/ theorem metric_bound : answerNetwork.length ≤ (sorry : ℕ) := sorry end SortingNetworkSize16