adaptive_merge.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. (void)l_block;
  103. (void)use_internal_buf;
  104. size_type n_keys = collected-l_intbuf;
  105. size_type len = len1+len2;
  106. if (!xbuf_used || n_keys) {
  107. xbuf.clear();
  108. const size_type middle = xbuf_used && n_keys ? n_keys: collected;
  109. unstable_sort(first, first + middle, comp, xbuf);
  110. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A k/b srt: ", len);
  111. stable_merge(first, first + middle, first + len, comp, xbuf);
  112. }
  113. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" A fin mrg: ", len);
  114. }
  115. template<class SizeType>
  116. inline static SizeType adaptive_merge_n_keys_without_external_keys(SizeType l_block, SizeType len1, SizeType len2, SizeType l_intbuf)
  117. {
  118. typedef SizeType size_type;
  119. //This is the minimum number of keys to implement the ideal algorithm
  120. size_type n_keys = len1/l_block+len2/l_block;
  121. const size_type second_half_blocks = len2/l_block;
  122. const size_type first_half_aux = len1-l_intbuf;
  123. while(n_keys >= ((first_half_aux-n_keys)/l_block + second_half_blocks)){
  124. --n_keys;
  125. }
  126. ++n_keys;
  127. return n_keys;
  128. }
  129. template<class SizeType>
  130. inline static SizeType adaptive_merge_n_keys_with_external_keys(SizeType l_block, SizeType len1, SizeType len2, SizeType l_intbuf)
  131. {
  132. typedef SizeType size_type;
  133. //This is the minimum number of keys to implement the ideal algorithm
  134. size_type n_keys = (len1-l_intbuf)/l_block + len2/l_block;
  135. return n_keys;
  136. }
  137. template<class SizeType, class Xbuf>
  138. inline SizeType adaptive_merge_n_keys_intbuf(SizeType &rl_block, SizeType len1, SizeType len2, Xbuf & xbuf, SizeType &l_intbuf_inout)
  139. {
  140. typedef SizeType size_type;
  141. size_type l_block = rl_block;
  142. size_type l_intbuf = xbuf.capacity() >= l_block ? 0u : l_block;
  143. if (xbuf.capacity() > l_block){
  144. l_block = xbuf.capacity();
  145. }
  146. //This is the minimum number of keys to implement the ideal algorithm
  147. size_type n_keys = adaptive_merge_n_keys_without_external_keys(l_block, len1, len2, l_intbuf);
  148. BOOST_ASSERT(n_keys >= ((len1-l_intbuf-n_keys)/l_block + len2/l_block));
  149. if(xbuf.template supports_aligned_trailing<size_type>
  150. ( l_block
  151. , adaptive_merge_n_keys_with_external_keys(l_block, len1, len2, l_intbuf)))
  152. {
  153. n_keys = 0u;
  154. }
  155. l_intbuf_inout = l_intbuf;
  156. rl_block = l_block;
  157. return n_keys;
  158. }
  159. // Main explanation of the merge algorithm.
  160. //
  161. // csqrtlen = ceil(sqrt(len));
  162. //
  163. // * First, csqrtlen [to be used as buffer] + (len/csqrtlen - 1) [to be used as keys] => to_collect
  164. // unique elements are extracted from elements to be sorted and placed in the beginning of the range.
  165. //
  166. // * Step "combine_blocks": the leading (len1-to_collect) elements plus trailing len2 elements
  167. // are merged with a non-trivial ("smart") algorithm to form an ordered range trailing "len-to_collect" elements.
  168. //
  169. // Explanation of the "combine_blocks" step:
  170. //
  171. // * Trailing [first+to_collect, first+len1) elements are divided in groups of cqrtlen elements.
  172. // Remaining elements that can't form a group are grouped in front of those elements.
  173. // * Trailing [first+len1, first+len1+len2) elements are divided in groups of cqrtlen elements.
  174. // Remaining elements that can't form a group are grouped in the back of those elements.
  175. // * In parallel the following two steps are performed:
  176. // * Groups are selection-sorted by first or last element (depending whether they are going
  177. // to be merged to left or right) and keys are reordered accordingly as an imitation-buffer.
  178. // * Elements of each block pair are merged using the csqrtlen buffer taking into account
  179. // if they belong to the first half or second half (marked by the key).
  180. //
  181. // * In the final merge step leading "to_collect" elements are merged with rotations
  182. // with the rest of merged elements in the "combine_blocks" step.
  183. //
  184. // Corner cases:
  185. //
  186. // * If no "to_collect" elements can be extracted:
  187. //
  188. // * If more than a minimum number of elements is extracted
  189. // then reduces the number of elements used as buffer and keys in the
  190. // and "combine_blocks" steps. If "combine_blocks" has no enough keys due to this reduction
  191. // then uses a rotation based smart merge.
  192. //
  193. // * If the minimum number of keys can't be extracted, a rotation-based merge is performed.
  194. //
  195. // * If auxiliary memory is more or equal than min(len1, len2), a buffered merge is performed.
  196. //
  197. // * If the len1 or len2 are less than 2*csqrtlen then a rotation-based merge is performed.
  198. //
  199. // * If auxiliary memory is more than csqrtlen+n_keys*sizeof(std::size_t),
  200. // then no csqrtlen need to be extracted and "combine_blocks" will use integral
  201. // keys to combine blocks.
  202. template<class RandIt, class Compare, class XBuf>
  203. void adaptive_merge_impl
  204. ( RandIt first
  205. , typename iterator_traits<RandIt>::size_type len1
  206. , typename iterator_traits<RandIt>::size_type len2
  207. , Compare comp
  208. , XBuf & xbuf
  209. )
  210. {
  211. typedef typename iterator_traits<RandIt>::size_type size_type;
  212. if(xbuf.capacity() >= min_value<size_type>(len1, len2)){
  213. buffered_merge(first, first+len1, first+(len1+len2), comp, xbuf);
  214. }
  215. else{
  216. const size_type len = len1+len2;
  217. //Calculate ideal parameters and try to collect needed unique keys
  218. size_type l_block = size_type(ceil_sqrt(len));
  219. //One range is not big enough to extract keys and the internal buffer so a
  220. //rotation-based based merge will do just fine
  221. if(len1 <= l_block*2 || len2 <= l_block*2){
  222. merge_bufferless(first, first+len1, first+len1+len2, comp);
  223. return;
  224. }
  225. //Detail the number of keys and internal buffer. If xbuf has enough memory, no
  226. //internal buffer is needed so l_intbuf will remain 0.
  227. size_type l_intbuf = 0;
  228. size_type n_keys = adaptive_merge_n_keys_intbuf(l_block, len1, len2, xbuf, l_intbuf);
  229. size_type const to_collect = l_intbuf+n_keys;
  230. //Try to extract needed unique values from the first range
  231. size_type const collected = collect_unique(first, first+len1, to_collect, comp, xbuf);
  232. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1("\n A collect: ", len);
  233. //Not the minimum number of keys is not available on the first range, so fallback to rotations
  234. if(collected != to_collect && collected < 4){
  235. merge_bufferless(first, first+collected, first+len1, comp);
  236. merge_bufferless(first, first + len1, first + len1 + len2, comp);
  237. return;
  238. }
  239. //If not enough keys but more than minimum, adjust the internal buffer and key count
  240. bool use_internal_buf = collected == to_collect;
  241. if (!use_internal_buf){
  242. l_intbuf = 0u;
  243. n_keys = collected;
  244. l_block = lblock_for_combine(l_intbuf, n_keys, len, use_internal_buf);
  245. //If use_internal_buf is false, then then internal buffer will be zero and rotation-based combination will be used
  246. l_intbuf = use_internal_buf ? l_block : 0u;
  247. }
  248. bool const xbuf_used = collected == to_collect && xbuf.capacity() >= l_block;
  249. //Merge trailing elements using smart merges
  250. adaptive_merge_combine_blocks(first, len1, len2, collected, n_keys, l_block, use_internal_buf, xbuf_used, comp, xbuf);
  251. //Merge buffer and keys with the rest of the values
  252. adaptive_merge_final_merge (first, len1, len2, collected, l_intbuf, l_block, use_internal_buf, xbuf_used, comp, xbuf);
  253. }
  254. }
  255. } //namespace detail_adaptive {
  256. ///@endcond
  257. //! <b>Effects</b>: Merges two consecutive sorted ranges [first, middle) and [middle, last)
  258. //! into one sorted range [first, last) according to the given comparison function comp.
  259. //! The algorithm is stable (if there are equivalent elements in the original two ranges,
  260. //! the elements from the first range (preserving their original order) precede the elements
  261. //! from the second range (preserving their original order).
  262. //!
  263. //! <b>Requires</b>:
  264. //! - RandIt must meet the requirements of ValueSwappable and RandomAccessIterator.
  265. //! - The type of dereferenced RandIt must meet the requirements of MoveAssignable and MoveConstructible.
  266. //!
  267. //! <b>Parameters</b>:
  268. //! - first: the beginning of the first sorted range.
  269. //! - middle: the end of the first sorted range and the beginning of the second
  270. //! - last: the end of the second sorted range
  271. //! - comp: comparison function object which returns true if the first argument is is ordered before the second.
  272. //! - uninitialized, uninitialized_len: raw storage starting on "uninitialized", able to hold "uninitialized_len"
  273. //! elements of type iterator_traits<RandIt>::value_type. Maximum performance is achieved when uninitialized_len
  274. //! is min(std::distance(first, middle), std::distance(middle, last)).
  275. //!
  276. //! <b>Throws</b>: If comp throws or the move constructor, move assignment or swap of the type
  277. //! of dereferenced RandIt throws.
  278. //!
  279. //! <b>Complexity</b>: Always K x O(N) comparisons and move assignments/constructors/swaps.
  280. //! Constant factor for comparisons and data movement is minimized when uninitialized_len
  281. //! is min(std::distance(first, middle), std::distance(middle, last)).
  282. //! Pretty good enough performance is achieved when uninitialized_len is
  283. //! ceil(sqrt(std::distance(first, last)))*2.
  284. //!
  285. //! <b>Caution</b>: Experimental implementation, not production-ready.
  286. template<class RandIt, class Compare>
  287. void adaptive_merge( RandIt first, RandIt middle, RandIt last, Compare comp
  288. , typename iterator_traits<RandIt>::value_type* uninitialized = 0
  289. , typename iterator_traits<RandIt>::size_type uninitialized_len = 0)
  290. {
  291. typedef typename iterator_traits<RandIt>::size_type size_type;
  292. typedef typename iterator_traits<RandIt>::value_type value_type;
  293. if (first == middle || middle == last){
  294. return;
  295. }
  296. //Reduce ranges to merge if possible
  297. do {
  298. if (comp(*middle, *first)){
  299. break;
  300. }
  301. ++first;
  302. if (first == middle)
  303. return;
  304. } while(1);
  305. RandIt first_high(middle);
  306. --first_high;
  307. do {
  308. --last;
  309. if (comp(*last, *first_high)){
  310. ++last;
  311. break;
  312. }
  313. if (last == middle)
  314. return;
  315. } while(1);
  316. ::boost::movelib::adaptive_xbuf<value_type, value_type*, size_type> xbuf(uninitialized, size_type(uninitialized_len));
  317. ::boost::movelib::detail_adaptive::adaptive_merge_impl(first, size_type(middle - first), size_type(last - middle), comp, xbuf);
  318. }
  319. } //namespace movelib {
  320. } //namespace boost {
  321. #include <boost/move/detail/config_end.hpp>
  322. #endif //#define BOOST_MOVE_ADAPTIVE_MERGE_HPP