Suppose you have an array that you’d like to sort by another array. A common use case might be a set of arrays of somethings and for each something you generate a score in say [0,1]. Now you’d like to sort your somethings by their scores.
Concretely, say you have an array of scores:
1 2 |
|
and you want the indices of the sorted scores, ie
1 2 |
|
in R, you can always use order, as in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
You can do something similar in ruby:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
And finally in C++, you can leverage qsort_r
; this function was designed to be a reentrant / threadsafe qsort
so you’re given a void*
to pass a block of memory into your comparison function. You can use this to sort the indices array by the scores:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
which produces when run
1 2 3 4 5 |
|
Note the canonical way to sort somethings by a float in c++ is to bang everything into a struct or class and leverage qsort
on the structs/classes directly. However, this is often pretty inconvenient, and if you have a lot of whatever you want to sort, it’s too memory intensive to put everything into structs/classes with the sole addition of your score field.
I think it’s obvious why I prefer to program in R.
NB: I am developing for OS X; if you are targeting linux you’ll have to figure out how to link qsort_r
yourself. I think someone also decided to permute the argument order. Sigh.