Lexicographic Ordering

Overview

A lexicographic ordering of English words is the ordering of the words as found within a dictionary.

Iteration

We can find the next lexicographic ordering of an array via a procedure of "pivot", "swap", and "reverse".

[ a₁ a₂ ... aᵢ | aᵢ₊₁ aᵢ₊₂ ... aₙ ]

Here the RHS side is the longest increasing sequence we could find, from right to left. That is, ai+1>ai+2>>an. Denote ai as the pivot. Next, swap the smallest element in the RHS greater than ai, say aj, with ai. This produces

[ a₁ a₂ ... aⱼ | aᵢ₊₁ aᵢ₊₂ ... aᵢ ... aₙ ]

Notice the RHS remains in sorted order. Since aj was the next smallest element, reversing the reverse-sorted RHS produces the next permutation, lexicographically speaking:

[ a₁ a₂ ... aⱼ | aₙ ... aᵢ ... aᵢ₊₂ aᵢ₊₁ ]

Eventually the swapped aj will be the largest in the RHS ensuring that the breakpoint will eventually move one more position leftward.

Powered by Forestry.md