I’m trying to sort an array A whose elements are indexes. The indexes refer to another array B whose value will determine the order of A. So, I would like to sort A such that B[ A[i] ] is increasing.
For example:
A = [0, 1, 4, 5, 7] B = [5, 3, 8, 2, 2, 7, 1, 6, 3, 9]
Sorted A would be
A' = [ 7, 4, 1, 0, 5 ]
Is this possible with C’s built-in sort, or am I going to have to write my own implementation?
EDIT: These arrays are local function variables.
If you want to use
qsort, the best thing to-do would be to re-wrap the indexes in A and the values in B into a struct, and then make a comparator based on a new array that struct. For instance:Now you can run
qsorton the struct array and from there you can extract the proper sorted sequence you desired for the original arrayAwithout having to use a custom sorting function.