So, actually what I need is to keep the index of old array after sorted. So for example if I input [2,4,1,5,7,9,6]
then the output is [2,0,1,3,6,4,5]
. I already have use qsort
and it works very well if there are no duplicate elements.
If there are duplicate elements, sometimes the first duplicate element was put last. For example, if the input is [5,4,6,5,2,1,3]
, what I want to be output is [5,4,6,1,0,3,2]
. So, 5
which have index 0
put before 5
which have index 3
. But, using qsort
sometimes make the output [5,4,6,1,3,0,2]
.
Can you help me to fix this? Or should I create my own sorting function? Could you please help me to create it?
Here is my code:
#include <stdlib.h>
int* sortidx(double *X,int n)
{
int *idx,i,j;
int cmp(const void *a,const void *b)
{
return X[*(int*)a]>=X[*(int*)b]?1:-1;
}
idx=(int*)calloc(n,sizeof(int));
for(i=0;i<n;i++)
{
idx[i]=i;
}
qsort(idx,n,sizeof(int),cmp);
return idx;
}