sort_utils.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #ifndef PLANCK_SORT_UTILS_H
00033 #define PLANCK_SORT_UTILS_H
00034
00035 #include <algorithm>
00036 #include <functional>
00037 #include <vector>
00038
00039 template<typename It, typename Comp> class IdxComp__
00040 {
00041 private:
00042 It begin;
00043 Comp comp;
00044 public:
00045 IdxComp__ (It begin_, Comp comp_): begin(begin_), comp(comp_) {}
00046 bool operator() (std::size_t a, std::size_t b) const
00047 { return comp(*(begin+a),*(begin+b)); }
00048 };
00049
00050
00051
00052
00053 template<typename It, typename T2, typename Comp>
00054 inline void buildIndex (It begin, It end, std::vector<T2> &idx, Comp comp)
00055 {
00056 using namespace std;
00057 T2 num=end-begin;
00058 idx.resize(num);
00059 for (T2 i=0; i<num; ++i) idx[i] = i;
00060 sort (idx.begin(),idx.end(),IdxComp__<It,Comp>(begin,comp));
00061 }
00062
00063
00064
00065
00066 template<typename It, typename T2> inline void buildIndex (It begin, It end,
00067 std::vector<T2> &idx)
00068 {
00069 using namespace std;
00070 typedef typename iterator_traits<It>::value_type T;
00071 buildIndex(begin,end,idx,less<T>());
00072 }
00073
00074
00075
00076 template<typename It, typename T2> inline void sortByIndex (It begin, It end,
00077 const std::vector<T2> &idx)
00078 {
00079 using namespace std;
00080 typedef typename iterator_traits<It>::value_type T;
00081 T2 num=end-begin;
00082 T *tmp= new T[num];
00083 for (T2 i=0; i<num; ++i) swap(tmp[i],*(begin+i));
00084 for (T2 i=0; i<num; ++i) swap(*(begin+i),tmp[idx[i]]);
00085 delete[] tmp;
00086 }
00087
00088
00089
00090 template<typename It, typename T2> inline void sortByIndex_inplace
00091 (It begin, It end, const std::vector<T2> &idx)
00092 {
00093 using namespace std;
00094 typedef typename iterator_traits<It>::value_type T;
00095 T2 num=end-begin;
00096 vector<bool> done(num,false);
00097 T2 cnt=0;
00098 while (cnt<num)
00099 {
00100 if (!done[cnt])
00101 {
00102 T tmp(*(begin+cnt));
00103 T2 cnt2 = cnt;
00104 T2 cnt3 = idx[cnt];
00105 while (cnt3!=cnt)
00106 {
00107 done[cnt2]=true;
00108 *(begin+cnt2)=*(begin+cnt3);
00109 cnt2=cnt3;
00110 cnt3=idx[cnt3];
00111 }
00112 *(begin+cnt2) = tmp;
00113 }
00114 ++cnt;
00115 }
00116 }
00117
00118 template<typename It, typename Comp> inline void indirectSort (It begin, It end,
00119 Comp comp)
00120 {
00121 using namespace std;
00122 vector<std::size_t> idx;
00123 buildIndex (begin,end,idx,comp);
00124 sortByIndex (begin,end,idx);
00125 }
00126
00127 template<typename It> inline void indirectSort (It begin, It end)
00128 {
00129 using namespace std;
00130 typedef typename iterator_traits<It>::value_type T;
00131 indirectSort(begin,end,less<T>());
00132 }
00133
00134 #endif