Skip to content

Instantly share code, notes, and snippets.

@tonigi
Created June 30, 2014 08:04
Show Gist options
  • Save tonigi/25abe7e05f4665cc6483 to your computer and use it in GitHub Desktop.
Save tonigi/25abe7e05f4665cc6483 to your computer and use it in GitHub Desktop.
Indices after sorting in C
/* Index sort. A sort function which returns indices as well as the
* sorted values. Tested with gcc only. T. Giorgino 2014
*/
#include <stdlib.h>
#ifndef _ISORT
#define _ISORT
const int descend = 1;
/* Somebody left this out of stdlib */
struct sort_pair {
double x;
size_t i;
};
int sort_cmp (const struct sort_pair *a, const struct sort_pair *b)
{
int r= (a->x > b->x) - (a->x < b->x);
if(descend)
return -r;
else
return r;
}
/* Return sorted values AND indices.
Inputs: double *in - input values
size_t N - length of the input
Outputs: double *out - sorted values
size_t *idx - indices after sorting
Caller is responsible for allocating memory
*/
void isort(const double *in, size_t N,
double *out, size_t *idx) {
struct sort_pair *tosort=malloc(sizeof(struct sort_pair)*N);
for(size_t i=0; i<N; i++) {
tosort[i].x=in[i];
tosort[i].i=i;
}
qsort(tosort,N,sizeof(struct sort_pair), (__compar_fn_t) sort_cmp);
for(size_t i=0; i<N; i++) {
out[i]=tosort[i].x;
idx[i]=tosort[i].i;
}
free(tosort);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment