fork download
  1. #include <algorithm>
  2. #include <iostream>
  3.  
  4. struct IndexSorter
  5. {
  6. double *m_array;
  7. IndexSorter(double *oArray) : m_array(oArray) {}
  8. bool operator()(long v1, long v2) const { return m_array[v1] < m_array[v2]; }
  9. };
  10.  
  11. long* IndexSort(unsigned long int vectorLength, double* column)
  12. {
  13. long *index = new long[vectorLength](); // I really don't recommend this line
  14. for (unsigned long i = 0; i < vectorLength; ++i)
  15. index[i] = i;
  16.  
  17. std::sort(index, index + vectorLength, IndexSorter(column));
  18. return index;
  19. }
  20.  
  21. using namespace std;
  22.  
  23. int main()
  24. {
  25. double testData[] = {0.8147,0.9058,0.127,0.9134,0.6324,0.0975,0.2785,
  26. 0.5469,0.9575,0.9649,0.1576,0.9706,0.9572,0.4854,
  27. 0.8003,0.1419,0.4218,0.9157,0.7922,0.9595};
  28. unsigned long testSize = sizeof(testData) / sizeof(testData[0]);
  29. long *indices = IndexSort(testSize, &testData[0]);
  30. for (unsigned long i = 0; i < testSize; ++i )
  31. cout << testData[indices[i]] << " has an index of " << indices[i] << "\n";
  32. delete [] indices;
  33. }
  34.  
  35.  
Success #stdin #stdout 0s 2816KB
stdin
Standard input is empty
stdout
0.0975  has an index of 5
0.127  has an index of 2
0.1419  has an index of 15
0.1576  has an index of 10
0.2785  has an index of 6
0.4218  has an index of 16
0.4854  has an index of 13
0.5469  has an index of 7
0.6324  has an index of 4
0.7922  has an index of 18
0.8003  has an index of 14
0.8147  has an index of 0
0.9058  has an index of 1
0.9134  has an index of 3
0.9157  has an index of 17
0.9572  has an index of 12
0.9575  has an index of 8
0.9595  has an index of 19
0.9649  has an index of 9
0.9706  has an index of 11