fr**********@hotmail.com wrote:
Hi all you C boffins:
I need to sort a vector of doubles is ascending order. Qsort will
return the sorted vector, but I need a vector of the indices of the
sorted vector, not the actual sorted vector. Any ideas?
Set up a parallel vector containing the indices,
initialize them to 0,1,...,(N-1), and qsort() that
array. Use a comparison function that compares not
the index values themselves, but the values in the
array of doubles, e.g.:
double values[] = { ... };
int compare(const void *pp, const void *qq) {
/* Get pointers to the indices */
const int *p = pp, *q = qq;
/* Get values at those array slots */
double v1 = values[*p], v2 = values[*q];
/* Compare those values */
return (v1 > v2) - (v1 < v2);
}
After sorting, index[0] will hold the index of the
smallest element in values[], index[1] the second
smallest, ..., index[N-1] the largest.
--
Er*********@sun.com