Is it more efficient to begin with a possibly random ordering of objects in a range, using next_permutation to step through all greater permutations, followed by stepping down, beginning again with the original ordering, using prev_permutation to reach the last.
Or, to sort the range before permuting, then to use only next_permutation to step through all of them?
next_permutationwill step through all permutations, not only through greater permutations. No need to revert and useprev_permutation, and certainly no need to sort.You only need take care of the fact that
next_permutationwill returnfalseonce it “rolls over” into the lexicographically lowest permutation so you need to keep track of the number of the current permutation to know when to stop.That is, the following will iterate through all possible permutations of a range, no matter how the starting range looks like.
Where
multinomial_coefficientis the multinomial coefficient of the number of distinct elements in the range. In the simple case where all elements are distinct, this is equivalent to N!, the factorial of the number of elements.