fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3.  
  4. static double *myArray;
  5.  
  6. int compareIndices(const void* v1, const void *v2)
  7. {
  8. long val1 = *(long *)v1;
  9. long val2 = *(long *)v2;
  10. if (myArray[val1] < myArray[val2])
  11. return -1;
  12. else
  13. if ( myArray[val1] > myArray[val2])
  14. return 1;
  15. return 0;
  16. }
  17.  
  18. long* IndexSort(unsigned long int vectorLength, double* column)
  19. {
  20. myArray = column;
  21. long *index = malloc(vectorLength * sizeof(long));
  22. if ( index )
  23. {
  24. unsigned long i;
  25. for (i = 0; i < vectorLength; ++i)
  26. index[i] = i;
  27. qsort(index, vectorLength, sizeof(long), compareIndices);
  28. return index;
  29. }
  30. return 0;
  31. }
  32.  
  33. int main()
  34. {
  35. double testData[] = { 0.8147, 0.9058, 0.127, 0.9134, 0.6324, 0.0975, 0.2785,
  36. 0.5469, 0.9575, 0.9649, 0.1576, 0.9706, 0.9572, 0.4854,
  37. 0.8003, 0.1419, 0.4218, 0.9157, 0.7922, 0.9595 };
  38. unsigned long numItems = sizeof(testData) / sizeof(testData[0]);
  39. long *indices = IndexSort(numItems, testData);
  40. if ( indices )
  41. {
  42. for (unsigned long i = 0; i < numItems; ++i)
  43. printf("%lf has an index of %ld\n", testData[indices[i]], indices[i]);
  44. free(indices);
  45. }
  46. }
Success #stdin #stdout 0s 2140KB
stdin
Standard input is empty
stdout
0.097500 has an index of 5
0.127000 has an index of 2
0.141900 has an index of 15
0.157600 has an index of 10
0.278500 has an index of 6
0.421800 has an index of 16
0.485400 has an index of 13
0.546900 has an index of 7
0.632400 has an index of 4
0.792200 has an index of 18
0.800300 has an index of 14
0.814700 has an index of 0
0.905800 has an index of 1
0.913400 has an index of 3
0.915700 has an index of 17
0.957200 has an index of 12
0.957500 has an index of 8
0.959500 has an index of 19
0.964900 has an index of 9
0.970600 has an index of 11