oILAB
Loading...
Searching...
No Matches
sortIndices.h
Go to the documentation of this file.
1//
2// Created by Nikhil Chandra Admal on 9/30/22.
3// https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes
4
5#ifndef OILAB_SORTINDICES_H
6#define OILAB_SORTINDICES_H
7
8#include <iostream>
9#include <vector>
10#include <numeric> // std::iota
11#include <algorithm> // std::sort, std::stable_sort
12
13using namespace std;
14
15namespace gbLAB {
16 template<typename ArrayType>
17 vector <size_t> sortIndices(const ArrayType &v) {
18
19 // initialize original index locations
20 vector<size_t> idx(v.size());
21 iota(idx.begin(), idx.end(), 0);
22
23 // sort indexes based on comparing values in v
24 // using std::stable_sort instead of std::sort
25 // to avoid unnecessary index re-orderings
26 // when v contains elements of equal values
27 stable_sort(idx.begin(), idx.end(),
28 [&v](size_t i1, size_t i2) { return abs(v(i1)) > abs(v(i2)); });
29
30 return idx;
31 }
32}
33#endif //OILAB_SORTINDICES_H
vector< size_t > sortIndices(const ArrayType &v)
Definition sortIndices.h:17