std::sort (and related) is one of the crown jewels of the STL.
However, when I try to use it in the context of numerical linear algebra, I find a glaring problem with it, which prevents me from using it.
The key is that in mathematics, keeping track of the parity (even/odd) of a permutation is usually relevant.
I can think of 3 ways to keep track of the parity:
- zip the sorting range with a trivial
0, 1... nsequence and read the permutation after sorting. (this is a sure way, but it does an unreasonable amount of extra work). - hack the comparison operation to flip a sign each time a given pair is unsorted. Of course, this is bound to fail in general, as I don't know if the number of permutations is the same as the number of "failed" comparisons.
- wrap the sequence in a type with a custom swap that has the side-effect of keeping a count or the sign of the permutations so far.
Of course, these are all horrible solutions; I am looking for something better if it is available: Is there an algorithm close to std::sort that could allow me to keep track of the parity without having to reimplement sort from scratch?
As suggested, you can just sort indices (with comparator function based on the original array at those indices). The parity can then be checked by an O(n) function following cycles in the permuted indices.