fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <array>
  4.  
  5. long* IndexSort(unsigned long int vectorLength, double* column)
  6. {
  7. long *index = new long[vectorLength](); // I really don't recommend this line
  8. long n = 0;
  9. std::generate( index, index + vectorLength, [&] { return n++; });
  10. std::sort(index, index + vectorLength, [&](long v1, long v2)
  11. { return column[v1] < column[v2]; });
  12. return index;
  13. }
  14.  
  15. using namespace std;
  16.  
  17. int main()
  18. {
  19. std::array<double,20> testData =
  20. {0.8147,0.9058,0.127,0.9134,0.6324,0.0975,0.2785,
  21. 0.5469,0.9575,0.9649,0.1576,0.9706,0.9572,0.4854,
  22. 0.8003,0.1419,0.4218,0.9157,0.7922,0.9595};
  23. long *indices = IndexSort(testData.size(), &testData[0]);
  24. for (size_t i = 0; i < testData.size(); ++i )
  25. cout << testData[indices[i]] << " has an index of " << indices[i] << "\n";
  26. delete [] indices;
  27. }
Success #stdin #stdout 0s 3232KB
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