Skip to content

Instantly share code, notes, and snippets.

@HViktorTsoi
Created June 21, 2020 07:23
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save HViktorTsoi/58eabb4f7c5a303ced400bcfa816f6f5 to your computer and use it in GitHub Desktop.
Save HViktorTsoi/58eabb4f7c5a303ced400bcfa816f6f5 to your computer and use it in GitHub Desktop.
C++ STL implementation of Argsort
#include <vector>
#include <algorithm>
/**
* Argsort(currently support ascending sort)
* @tparam T array element type
* @param array input array
* @return indices w.r.t sorted array
*/
template<typename T>
std::vector<size_t> argsort(const std::vector<T> &array) {
std::vector<size_t> indices(array.size());
std::iota(indices.begin(), indices.end(), 0);
std::sort(indices.begin(), indices.end(),
[&array](int left, int right) -> bool {
// sort indices according to corresponding array element
return array[left] < array[right];
});
return indices;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment