-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsortidx.h
58 lines (49 loc) · 1.55 KB
/
sortidx.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/******************************************************************************
* Version: 1.0
* Last modified on: 21 January, 2013
* Developers: Michael G. Epitropakis, Xiaodong Li.
* email: mge_(AT)_cs_(DOT)_stir_(DOT)_ac_(DOT)_uk
* : xiaodong_(DOT)_li_(AT)_rmit_(DOT)_edu_(DOT)_au
* ***************************************************************************/
#ifndef __SORT_IND_H__
#define __SORT_IND_H__
/** Sort indexes based on a vector of values
* based on: http://ideone.com/HOnvI
**/
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <utility>
enum {ASCEND, DESCEND};
template<typename T>
bool ascend_sort(std::pair<size_t, T> i, std::pair<size_t, T> j) {
return j.second < i.second;
}
template<typename T>
bool descend_sort(std::pair<size_t, T> i, std::pair<size_t, T> j) {
return i.second > j.second;
}
template<typename T>
void sortIdx(std::vector<size_t>& idx, const std::vector<T>& src, const int &dir=ASCEND)
{
/* Resize idx to the src.size() */
idx.resize(src.size());
/* Create a vector of pairs (tmp) */
std::vector< std::pair<size_t, T> > tmp;
for (size_t i=0; i<src.size(); ++i) {
tmp.push_back(std::pair<size_t, T> (i, src[i]));
}
/* Sort indeces ASCEND/DESCEND */
if (dir == ASCEND) {
sort(tmp.begin(), tmp.end(), ascend_sort<T>);
} else {
sort(tmp.begin(), tmp.end(), descend_sort<T>);
}
/* put sorted indeces to idx vector */
for (size_t i=0; i<src.size(); i++){
idx[i] = (tmp[i].first);
//std::cout << tmp[i].first << " " << tmp[i].second << std::endl;
}
}
#endif