Batcher sorting on finite tuples #
The algorithm sorts a power-of-two tuple of records by a separate key. Each layer compares corresponding records in two halves and moves whole records. Ascending comparisons retain ties; descending comparisons reverse the ascending result, including ties. The complete sorter is not a stable sorting algorithm.
Main definitions #
Cslib.BitonicSort.arity: the power-of-two number of records, with a definitional split.Cslib.BitonicSort.IsBitonic: the four-point lattice invariant used by bitonic merge.Cslib.BitonicSort.compareLayer: one layer of independent comparisons.Cslib.BitonicSort.merge: recursively merge a bitonic tuple.Cslib.BitonicSort.sort: Batcher's recursive sorter.Cslib.BitonicSort.mergeVector,Cslib.BitonicSort.sortVector: the same algorithms on vectors, storing each layer once.Cslib.BitonicSort.sortImpl: compiler implementation ofsortthat reads the stored vector from depth 2 on.
Main results #
Cslib.BitonicSort.compareLayer_perm,Cslib.BitonicSort.merge_perm, andCslib.BitonicSort.sort_perm: each stage preserves the multiset of complete records.Cslib.BitonicSort.get_mergeVector,Cslib.BitonicSort.get_sortVector: the stored vectors agree withmergeandsort.Cslib.BitonicSort.sort_eq_sortImpl: proved compiler replacement, so from depth 2 on executedsortreads each layer from a vector instead of recomputing it through nested closures. The compiler appliessortImplto the index as well, so each executed read of asortresult rebuilds the vector. This module does not certify a runtime bound.
References #
- K. E. Batcher, Sorting Networks and Their Applications.
- Adapted from MassProduction/SortingSemantics/Defs.lean and MassProduction/SortingSemantics/Internal.lean in S. Schlesinger, Boolean circuit mass production formalization.
The number of records at a given depth, with a definitional split into two equal halves.
Four-point lattice invariant for bitonic merge. The four indices are in cyclic order; the two inequalities exclude alternating high and low values.
Compare corresponding records in the two halves. Descending order reverses the ascending comparison, so descending ties are exchanged.
A layer preserves the multiset of complete records, even when some keys agree.
Bitonic merge preserves the multiset of complete records on every input.
Batcher sorting preserves complete records, not merely their projected keys.
Bitonic merge on a vector. Each layer and each merged half is stored once, so a record is read from the previous layer without recomputing earlier layers.
The stored merge agrees with merge.
The stored sort agrees with sort.
Compiler implementation of sort, reading a stored vector from depth 2 on. Depths 0 and 1
keep the closures, which are cheaper there. The compiler applies it to the index as well, so each
executed read rebuilds the vector; callers that read every entry can keep sortVector.