In C++ would like to sort a lengthy (2^20
) vector of reals, obviously sort()
does the trick. Having used R before I was used to the nice order()
function which yields the permutation that leads to the sorted vector.
Example:
x = {24, 55, 22, 1}
Then the permutation
perm = {3, 2, 0, 1}
Maps the original x
to the sorted x
in ascending order.
I can probably implement some bubble sort which does not only sort x but performs the same transpositions on the vector {0,1,2,...}
and outputs both, but I believe someone must have thought about it and especially have done it efficiently.
You can use
std::sort
to sort the list of pairs {(24, 0), (55, 2), (22, 0), (1, 1)}. It isn't particularly pretty, but I usually do something like this:Here is the test:
Edit
Better than before approach without using helper vectors: (source on ideone):
I am using lambda from C++0x, but it can be replaced with simple functor object:
Source of old solution with
std::map
: ideoneI would say the best way would be to create a vector of ints 0..N and then sort that array with a comparison function that compares the corresponding elements of the vector you're trying to find the sorted permutation of. Something like:
This minimizes the allocation overhead, as we don't create any large temporary object that we sort and then extract the final permution -- the same vector that is being returned is the temp for sorting.