So actually I need to keep the index of the old array after sorting. So, for example, if I enter [2,4,1,5,7,9,6], then there will be a way out [2,0,1,3,6,4,5]. I already have qsortit and it works very well if there are no duplicate elements.
If there are repeating elements, sometimes the first repeating element was placed last. For example, if the input is [5,4,6,5,2,1,3]what I want to deduce [5,4,6,1,0,3,2]. So, 5those that have an index 0are placed in front of 5that have an index 3. But using qsort, sometimes we conclude [5,4,6,1,3,0,2].
Can you help me fix this? Or should I create my own sort function? Could you help me 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;
}