Generating permutations with number of inversions below a fixed amount

algorithmscombinatorics

Is anyone aware of an algorithm to generate all permutations of the set $\left\{0, 1, \ldots, n-1\right\}$ with fewer than $k$ inversions for
$0 < k < n$? Ideally, the algorithm should generate the permutations in-place through a sequence of swaps starting with the array $\left[0, 1, \ldots, n-1\right]$. The application is finding maximal values for functions $f$ defined over permutations which are bounded above by a function $g$ of the number of inversions. No condition is needed on the order in the which the permutations are generated. The goal is to iterate through all permutations with fewer than $k$ inversions through a series of swaps, while only storing an array of length $n$ containing the current permutation along with an $O(n)$ amount of additional storage that helps speed up computation of which swaps to make.

Currently I'm using the Steinhaus-Johnson-Trotter Algorithm with Even's speedup to generate all permutations in-place. As an aside, the description of Even's speedup in the linked Wikipedia article is missing key information, however a complete implementation is described in Shimon Even's Algorithmic Combinatorics (1973) and my implementation is available here. It uses $O(n)$ additional storage to compute which swap to make in amortized $O(1)$ time.

My current approach is for the most part good enough because the values of $n$ are typically small. However, an efficient algorithm to generate permutations with fewer than $k$ inversions would give a nice optimization that could help in some rare cases.

Update: I ended up making some low hanging fruit optimizations that made my algorithm efficient enough for all practical cases. I’ve accepted Peter Taylor’s answer. It would have been possible to use it for my application by keeping an explicit stack of the swaps that have been made, along with the number of inversions.

Best Answer

Consider the Cayley graph generated by adjacent swaps $T_i = (i, i+1)$. These swaps generate the symmetric group and their Cayley graph is layered by the number in inversions. To walk over the first $k$ layers you could use breadth-first search, but that uses a lot of memory. For practical implementation you probably want depth-first search, and to avoid duplicates you want to limit each vertex to one incoming edge in any deterministic way. (E.g. you could look at the lowest $i$ such that $T_i$ gives an in-edge).

Related Question