Originally Posted by
AssistMe
BUT....the problem is, when I sort the array, the array number will be gone and instead of printing 3,2,0,1......0,1,2,3 will be printed...
You have your array. Make an array of pointers to each array element. Sort the array of pointers based on the value they point to. Then take the difference of each pointer value in the sorted pointer array from the start of the array.
Code:
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
const float *const *x = a, *const *y = b;
return **x > **y ? 1 : **x < **y ? -1 : 0;
}
int main(void)
{
float array[] = { 3.40, 4.00, 1.30, 1.29 };
float *ptr [ sizeof array / sizeof *array ];
size_t i;
for (i = 0; i < sizeof ptr / sizeof *ptr; ++i )
{
ptr[i] = &array[i];
printf("%d (%g)\n", ptr[i] - array, *ptr[i]);
}
puts("--qsort--");
qsort(ptr, sizeof ptr / sizeof *ptr, sizeof *ptr, compare);
for (i = 0; i < sizeof ptr / sizeof *ptr; ++i )
{
printf("%d (%g)\n", ptr[i] - array, *ptr[i]);
}
return 0;
}
/* my output
0 (3.4)
1 (4)
2 (1.3)
3 (1.29)
--qsort--
3 (1.29)
2 (1.3)
0 (3.4)
1 (4)
*/