Sorting a vector in ascending order

F

fred_stevens

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?

Thanks in advance,
Fred.
 
E

Eric Sosman

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.
 
F

fred_stevens

Eric said:
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.

Thanks very much Eric. I'll give that a try.

Fred.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top