adaptive_merge.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2015-2016.
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // See http://www.boost.org/libs/move for documentation.
  9. //
  10. //////////////////////////////////////////////////////////////////////////////
  11. #ifndef BOOST_MOVE_ADAPTIVE_MERGE_HPP
  12. #define BOOST_MOVE_ADAPTIVE_MERGE_HPP
  13. #include <boost/move/detail/config_begin.hpp>
  14. #include <boost/move/algo/detail/adaptive_sort_merge.hpp>
  15. namespace boost {
  16. namespace movelib {
  17. ///@cond
  18. namespace detail_adaptive {
  19. template<class RandIt, class Compare, class XBuf>
  20. inline void adaptive_merge_combine_blocks( RandIt first
  21. , typename iterator_traits<RandIt>::size_type len1
  22. , typename iterator_traits<RandIt>::size_type len2
  23. , typename iterator_traits<RandIt>::size_type collected
  24. , typename iterator_traits<RandIt>::size_type n_keys
  25. , typename iterator_traits<RandIt>::size_type l_block
  26. , bool use_internal_buf
  27. , bool xbuf_used
  28. , Compare comp
  29. , XBuf & xbuf
  30. )
  31. {
  32. typedef typename iterator_traits<RandIt>::size_type size_type;
  33. size_type const len = len1+len2;
  34. size_type const l_combine = len-collected;
  35. size_type const l_combine1 = len1-collected;
  36. if(n_keys){
  37. RandIt const first_data = first+collected;
  38. RandIt const keys = first;
  39. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A combine: ", len);
  40. if(xbuf_used){
  41. if(xbuf.size() < l_block){
  42. xbuf.initialize_until(l_block, *first);
  43. }
  44. BOOST_ASSERT(xbuf.size() >= l_block);
  45. size_type n_block_a, n_block_b, l_irreg1, l_irreg2;
  46. combine_params( keys, comp, l_combine
  47. , l_combine1, l_block, xbuf
  48. , n_block_a, n_block_b, l_irreg1, l_irreg2); //Outputs
  49. op_merge_blocks_with_buf
  50. (keys, comp, first_data, l_block, l_irreg1, n_block_a, n_block_b, l_irreg2, comp, move_op(), xbuf.data());
  51. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" A mrg xbf: ", len);
  52. }
  53. else{
  54. size_type n_block_a, n_block_b, l_irreg1, l_irreg2;
  55. combine_params( keys, comp, l_combine
  56. , l_combine1, l_block, xbuf
  57. , n_block_a, n_block_b, l_irreg1, l_irreg2); //Outputs
  58. if(use_internal_buf){
  59. op_merge_blocks_with_buf
  60. (keys, comp, first_data, l_block, l_irreg1, n_block_a, n_block_b, l_irreg2, comp, swap_op(), first_data-l_block);
  61. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A mrg buf: ", len);
  62. }
  63. else{
  64. merge_blocks_bufferless
  65. (keys, comp, first_data, l_block, l_irreg1, n_block_a, n_block_b, l_irreg2, comp);
  66. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" A mrg nbf: ", len);
  67. }
  68. }
  69. }
  70. else{
  71. xbuf.shrink_to_fit(l_block);
  72. if(xbuf.size() < l_block){
  73. xbuf.initialize_until(l_block, *first);
  74. }
  75. size_type *const uint_keys = xbuf.template aligned_trailing<size_type>(l_block);
  76. size_type n_block_a, n_block_b, l_irreg1, l_irreg2;
  77. combine_params( uint_keys, less(), l_combine
  78. , l_combine1, l_block, xbuf
  79. , n_block_a, n_block_b, l_irreg1, l_irreg2, true); //Outputs
  80. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A combine: ", len);
  81. BOOST_ASSERT(xbuf.size() >= l_block);
  82. op_merge_blocks_with_buf
  83. (uint_keys, less(), first, l_block, l_irreg1, n_block_a, n_block_b, l_irreg2, comp, move_op(), xbuf.data());
  84. xbuf.clear();
  85. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" A mrg buf: ", len);
  86. }
  87. }
  88. template<class RandIt, class Compare, class XBuf>
  89. inline void adaptive_merge_final_merge( RandIt first
  90. , typename iterator_traits<RandIt>::size_type len1
  91. , typename iterator_traits<RandIt>::size_type len2
  92. , typename iterator_traits<RandIt>::size_type collected
  93. , typename iterator_traits<RandIt>::size_type l_intbuf
  94. , typename iterator_traits<RandIt>::size_type //l_block
  95. , bool //use_internal_buf
  96. , bool xbuf_used
  97. , Compare comp
  98. , XBuf & xbuf
  99. )
  100. {
  101. typedef typename iterator_traits<RandIt>::size_type size_type;
  102. size_type n_keys = collected-l_intbuf;
  103. size_type len = len1+len2;
  104. if (!xbuf_used || n_keys) {
  105. xbuf.clear();
  106. const size_type middle = xbuf_used && n_keys ? n_keys: collected;
  107. unstable_sort(first, first + middle, comp, xbuf);
  108. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A k/b srt: ", len);
  109. stable_merge(first, first + middle, first + len, comp, xbuf);
  110. }
  111. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" A fin mrg: ", len);
  112. }
  113. template<class SizeType>
  114. inline static SizeType adaptive_merge_n_keys_without_external_keys(SizeType l_block, SizeType len1, SizeType len2, SizeType l_intbuf)
  115. {
  116. typedef SizeType size_type;
  117. //This is the minimum number of keys to implement the ideal algorithm
  118. size_type n_keys = len1/l_block+len2/l_block;
  119. const size_type second_half_blocks = len2/l_block;
  120. const size_type first_half_aux = len1-l_intbuf;
  121. while(n_keys >= ((first_half_aux-n_keys)/l_block + second_half_blocks)){
  122. --n_keys;
  123. }
  124. ++n_keys;
  125. return n_keys;
  126. }
  127. template<class SizeType>
  128. inline static SizeType adaptive_merge_n_keys_with_external_keys(SizeType l_block, SizeType len1, SizeType len2, SizeType l_intbuf)
  129. {
  130. typedef SizeType size_type;
  131. //This is the minimum number of keys to implement the ideal algorithm
  132. size_type n_keys = (len1-l_intbuf)/l_block + len2/l_block;
  133. return n_keys;
  134. }
  135. template<class SizeType, class Xbuf>
  136. inline SizeType adaptive_merge_n_keys_intbuf(SizeType &rl_block, SizeType len1, SizeType len2, Xbuf & xbuf, SizeType &l_intbuf_inout)
  137. {
  138. typedef SizeType size_type;
  139. size_type l_block = rl_block;
  140. size_type l_intbuf = xbuf.capacity() >= l_block ? 0u : l_block;
  141. if (xbuf.capacity() > l_block){
  142. l_block = xbuf.capacity();
  143. }
  144. //This is the minimum number of keys to implement the ideal algorithm
  145. size_type n_keys = adaptive_merge_n_keys_without_external_keys(l_block, len1, len2, l_intbuf);
  146. BOOST_ASSERT(n_keys >= ((len1-l_intbuf-n_keys)/l_block + len2/l_block));
  147. if(xbuf.template supports_aligned_trailing<size_type>
  148. ( l_block
  149. , adaptive_merge_n_keys_with_external_keys(l_block, len1, len2, l_intbuf)))
  150. {
  151. n_keys = 0u;
  152. }
  153. l_intbuf_inout = l_intbuf;
  154. rl_block = l_block;
  155. return n_keys;
  156. }
  157. // Main explanation of the merge algorithm.
  158. //
  159. // csqrtlen = ceil(sqrt(len));
  160. //
  161. // * First, csqrtlen [to be used as buffer] + (len/csqrtlen - 1) [to be used as keys] => to_collect
  162. // unique elements are extracted from elements to be sorted and placed in the beginning of the range.
  163. //
  164. // * Step "combine_blocks": the leading (len1-to_collect) elements plus trailing len2 elements
  165. // are merged with a non-trivial ("smart") algorithm to form an ordered range trailing "len-to_collect" elements.
  166. //
  167. // Explanation of the "combine_blocks" step:
  168. //
  169. // * Trailing [first+to_collect, first+len1) elements are divided in groups of cqrtlen elements.
  170. // Remaining elements that can't form a group are grouped in front of those elements.
  171. // * Trailing [first+len1, first+len1+len2) elements are divided in groups of cqrtlen elements.
  172. // Remaining elements that can't form a group are grouped in the back of those elements.
  173. // * In parallel the following two steps are performed:
  174. // * Groups are selection-sorted by first or last element (depending whether they are going
  175. // to be merged to left or right) and keys are reordered accordingly as an imitation-buffer.
  176. // * Elements of each block pair are merged using the csqrtlen buffer taking into account
  177. // if they belong to the first half or second half (marked by the key).
  178. //
  179. // * In the final merge step leading "to_collect" elements are merged with rotations
  180. // with the rest of merged elements in the "combine_blocks" step.
  181. //
  182. // Corner cases:
  183. //
  184. // * If no "to_collect" elements can be extracted:
  185. //
  186. // * If more than a minimum number of elements is extracted
  187. // then reduces the number of elements used as buffer and keys in the
  188. // and "combine_blocks" steps. If "combine_blocks" has no enough keys due to this reduction
  189. // then uses a rotation based smart merge.
  190. //
  191. // * If the minimum number of keys can't be extracted, a rotation-based merge is performed.
  192. //
  193. // * If auxiliary memory is more or equal than min(len1, len2), a buffered merge is performed.
  194. //
  195. // * If the len1 or len2 are less than 2*csqrtlen then a rotation-based merge is performed.
  196. //
  197. // * If auxiliary memory is more than csqrtlen+n_keys*sizeof(std::size_t),
  198. // then no csqrtlen need to be extracted and "combine_blocks" will use integral
  199. // keys to combine blocks.
  200. template<class RandIt, class Compare, class XBuf>
  201. void adaptive_merge_impl
  202. ( RandIt first
  203. , typename iterator_traits<RandIt>::size_type len1
  204. , typename iterator_traits<RandIt>::size_type len2
  205. , Compare comp
  206. , XBuf & xbuf
  207. )
  208. {
  209. typedef typename iterator_traits<RandIt>::size_type size_type;
  210. if(xbuf.capacity() >= min_value<size_type>(len1, len2)){
  211. buffered_merge(first, first+len1, first+(len1+len2), comp, xbuf);
  212. }
  213. else{
  214. const size_type len = len1+len2;
  215. //Calculate ideal parameters and try to collect needed unique keys
  216. size_type l_block = size_type(ceil_sqrt(len));
  217. //One range is not big enough to extract keys and the internal buffer so a
  218. //rotation-based based merge will do just fine
  219. if(len1 <= l_block*2 || len2 <= l_block*2){
  220. merge_bufferless(first, first+len1, first+len1+len2, comp);
  221. return;
  222. }
  223. //Detail the number of keys and internal buffer. If xbuf has enough memory, no
  224. //internal buffer is needed so l_intbuf will remain 0.
  225. size_type l_intbuf = 0;
  226. size_type n_keys = adaptive_merge_n_keys_intbuf(l_block, len1, len2, xbuf, l_intbuf);
  227. size_type const to_collect = l_intbuf+n_keys;
  228. //Try to extract needed unique values from the first range
  229. size_type const collected = collect_unique(first, first+len1, to_collect, comp, xbuf);
  230. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1("\n A collect: ", len);
  231. //Not the minimum number of keys is not available on the first range, so fallback to rotations
  232. if(collected != to_collect && collected < 4){
  233. merge_bufferless(first, first+collected, first+len1, comp);
  234. merge_bufferless(first, first + len1, first + len1 + len2, comp);
  235. return;
  236. }
  237. //If not enough keys but more than minimum, adjust the internal buffer and key count
  238. bool use_internal_buf = collected == to_collect;
  239. if (!use_internal_buf){
  240. l_intbuf = 0u;
  241. n_keys = collected;
  242. l_block = lblock_for_combine(l_intbuf, n_keys, len, use_internal_buf);
  243. //If use_internal_buf is false, then then internal buffer will be zero and rotation-based combination will be used
  244. l_intbuf = use_internal_buf ? l_block : 0u;
  245. }
  246. bool const xbuf_used = collected == to_collect && xbuf.capacity() >= l_block;
  247. //Merge trailing elements using smart merges
  248. adaptive_merge_combine_blocks(first, len1, len2, collected, n_keys, l_block, use_internal_buf, xbuf_used, comp, xbuf);
  249. //Merge buffer and keys with the rest of the values
  250. adaptive_merge_final_merge (first, len1, len2, collected, l_intbuf, l_block, use_internal_buf, xbuf_used, comp, xbuf);
  251. }
  252. }
  253. } //namespace detail_adaptive {
  254. ///@endcond
  255. //! <b>Effects</b>: Merges two consecutive sorted ranges [first, middle) and [middle, last)
  256. //! into one sorted range [first, last) according to the given comparison function comp.
  257. //! The algorithm is stable (if there are equivalent elements in the original two ranges,
  258. //! the elements from the first range (preserving their original order) precede the elements
  259. //! from the second range (preserving their original order).
  260. //!
  261. //! <b>Requires</b>:
  262. //! - RandIt must meet the requirements of ValueSwappable and RandomAccessIterator.
  263. //! - The type of dereferenced RandIt must meet the requirements of MoveAssignable and MoveConstructible.
  264. //!
  265. //! <b>Parameters</b>:
  266. //! - first: the beginning of the first sorted range.
  267. //! - middle: the end of the first sorted range and the beginning of the second
  268. //! - last: the end of the second sorted range
  269. //! - comp: comparison function object which returns true if the first argument is is ordered before the second.
  270. //! - uninitialized, uninitialized_len: raw storage starting on "uninitialized", able to hold "uninitialized_len"
  271. //! elements of type iterator_traits<RandIt>::value_type. Maximum performance is achieved when uninitialized_len
  272. //! is min(std::distance(first, middle), std::distance(middle, last)).
  273. //!
  274. //! <b>Throws</b>: If comp throws or the move constructor, move assignment or swap of the type
  275. //! of dereferenced RandIt throws.
  276. //!
  277. //! <b>Complexity</b>: Always K x O(N) comparisons and move assignments/constructors/swaps.
  278. //! Constant factor for comparisons and data movement is minimized when uninitialized_len
  279. //! is min(std::distance(first, middle), std::distance(middle, last)).
  280. //! Pretty good enough performance is achieved when uninitialized_len is
  281. //! ceil(sqrt(std::distance(first, last)))*2.
  282. //!
  283. //! <b>Caution</b>: Experimental implementation, not production-ready.
  284. template<class RandIt, class Compare>
  285. void adaptive_merge( RandIt first, RandIt middle, RandIt last, Compare comp
  286. , typename iterator_traits<RandIt>::value_type* uninitialized = 0
  287. , typename iterator_traits<RandIt>::size_type uninitialized_len = 0)
  288. {
  289. typedef typename iterator_traits<RandIt>::size_type size_type;
  290. typedef typename iterator_traits<RandIt>::value_type value_type;
  291. if (first == middle || middle == last){
  292. return;
  293. }
  294. //Reduce ranges to merge if possible
  295. do {
  296. if (comp(*middle, *first)){
  297. break;
  298. }
  299. ++first;
  300. if (first == middle)
  301. return;
  302. } while(1);
  303. RandIt first_high(middle);
  304. --first_high;
  305. do {
  306. --last;
  307. if (comp(*last, *first_high)){
  308. ++last;
  309. break;
  310. }
  311. if (last == middle)
  312. return;
  313. } while(1);
  314. ::boost::movelib::adaptive_xbuf<value_type, value_type*, size_type> xbuf(uninitialized, size_type(uninitialized_len));
  315. ::boost::movelib::detail_adaptive::adaptive_merge_impl(first, size_type(middle - first), size_type(last - middle), comp, xbuf);
  316. }
  317. } //namespace movelib {
  318. } //namespace boost {
  319. #include <boost/move/detail/config_end.hpp>
  320. #endif //#define BOOST_MOVE_ADAPTIVE_MERGE_HPP