TCPSPSuite
All Classes Functions Pages
sorting.hpp
1 //
2 // Created by lukas on 12.02.18.
3 //
4 
5 #ifndef TCPSPSUITE_SORTING_HPP
6 #define TCPSPSUITE_SORTING_HPP
7 
8 namespace algo {
9 
10 class DefaultIndexGetter {
11 public:
12  static unsigned int get(unsigned int i) { return i ; }
13 };
14 
15 template<class T, class IC, class IndexGetter = DefaultIndexGetter>
16 void apply_permutation(std::vector<T> & container, const IC & indices)
17 {
18  // TODO can we somehow get rid of this this bool vector?
19  std::vector<bool> done(container.size(), false);
20 
21  // TODO use moves everywhere!
22  for (unsigned int i = 0 ; i < container.size() ; ++i) {
23  if (done[i]) {
24  continue;
25  }
26 
27  T cpy = container[i];
28  unsigned int index = IndexGetter::get(indices[i]);
29  container[i] = container[index];
30 
31  while (IndexGetter::get(indices[index]) != i) {
32  container[index] = container[IndexGetter::get(indices[index])];
33  done[index] = true;
34  index = IndexGetter::get(indices[index]);
35  }
36 
37  container[index] = cpy;
38  done[index] = true;
39  }
40 }
41 
42 } // namespace algo
43 
44 #endif //TCPSPSUITE_SORTING_HPP