COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### Sorting a vector in ascending order #2

• Follow

```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?

Fred.

```
 0
Reply fred_stevens (3) 3/3/2005 7:28:29 PM

```
fred_stevens@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.

--
Eric.Sosman@sun.com

```
 0
Reply Eric.Sosman (4228) 3/3/2005 7:41:57 PM

```Eric Sosman wrote:
> fred_stevens@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.
>
> --
> Eric.Sosman@sun.com

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

Fred.

```
 0
Reply fred_stevens (3) 3/4/2005 12:12:59 AM

2 Replies
42 Views