adaptive_sort.hpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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_SORT_HPP
  12. #define BOOST_MOVE_ADAPTIVE_SORT_HPP
  13. #include <boost/move/detail/config_begin.hpp>
  14. #include <boost/move/algo/detail/adaptive_sort_merge.hpp>
  15. #include <cassert>
  16. #if defined(BOOST_CLANG) || (defined(BOOST_GCC) && (BOOST_GCC >= 40600))
  17. #pragma GCC diagnostic push
  18. #pragma GCC diagnostic ignored "-Wsign-conversion"
  19. #pragma GCC diagnostic ignored "-Wconversion"
  20. #endif
  21. namespace boost {
  22. namespace movelib {
  23. ///@cond
  24. namespace detail_adaptive {
  25. template<class RandIt>
  26. void move_data_backward( RandIt cur_pos
  27. , typename iter_size<RandIt>::type const l_data
  28. , RandIt new_pos
  29. , bool const xbuf_used)
  30. {
  31. //Move buffer to the total combination right
  32. if(xbuf_used){
  33. boost::move_backward(cur_pos, cur_pos+l_data, new_pos+l_data);
  34. }
  35. else{
  36. boost::adl_move_swap_ranges_backward(cur_pos, cur_pos+l_data, new_pos+l_data);
  37. //Rotate does less moves but it seems slower due to cache issues
  38. //rotate_gcd(first-l_block, first+len-l_block, first+len);
  39. }
  40. }
  41. template<class RandIt>
  42. void move_data_forward( RandIt cur_pos
  43. , typename iter_size<RandIt>::type const l_data
  44. , RandIt new_pos
  45. , bool const xbuf_used)
  46. {
  47. //Move buffer to the total combination right
  48. if(xbuf_used){
  49. boost::move(cur_pos, cur_pos+l_data, new_pos);
  50. }
  51. else{
  52. boost::adl_move_swap_ranges(cur_pos, cur_pos+l_data, new_pos);
  53. //Rotate does less moves but it seems slower due to cache issues
  54. //rotate_gcd(first-l_block, first+len-l_block, first+len);
  55. }
  56. }
  57. // build blocks of length 2*l_build_buf. l_build_buf is power of two
  58. // input: [0, l_build_buf) elements are buffer, rest unsorted elements
  59. // output: [0, l_build_buf) elements are buffer, blocks 2*l_build_buf and last subblock sorted
  60. //
  61. // First elements are merged from right to left until elements start
  62. // at first. All old elements [first, first + l_build_buf) are placed at the end
  63. // [first+len-l_build_buf, first+len). To achieve this:
  64. // - If we have external memory to merge, we save elements from the buffer
  65. // so that a non-swapping merge is used. Buffer elements are restored
  66. // at the end of the buffer from the external memory.
  67. //
  68. // - When the external memory is not available or it is insufficient
  69. // for a merge operation, left swap merging is used.
  70. //
  71. // Once elements are merged left to right in blocks of l_build_buf, then a single left
  72. // to right merge step is performed to achieve merged blocks of size 2K.
  73. // If external memory is available, usual merge is used, swap merging otherwise.
  74. //
  75. // As a last step, if auxiliary memory is available in-place merge is performed.
  76. // until all is merged or auxiliary memory is not large enough.
  77. template<class RandIt, class Compare, class XBuf>
  78. typename iter_size<RandIt>::type
  79. adaptive_sort_build_blocks
  80. ( RandIt const first
  81. , typename iter_size<RandIt>::type const len
  82. , typename iter_size<RandIt>::type const l_base
  83. , typename iter_size<RandIt>::type const l_build_buf
  84. , XBuf & xbuf
  85. , Compare comp)
  86. {
  87. typedef typename iter_size<RandIt>::type size_type;
  88. assert(l_build_buf <= len);
  89. assert(0 == ((l_build_buf / l_base)&(l_build_buf/l_base-1)));
  90. //Place the start pointer after the buffer
  91. RandIt first_block = first + l_build_buf;
  92. size_type const elements_in_blocks = size_type(len - l_build_buf);
  93. //////////////////////////////////
  94. // Start of merge to left step
  95. //////////////////////////////////
  96. size_type l_merged = 0u;
  97. assert(l_build_buf);
  98. //If there is no enough buffer for the insertion sort step, just avoid the external buffer
  99. size_type kbuf = min_value<size_type>(l_build_buf, size_type(xbuf.capacity()));
  100. kbuf = kbuf < l_base ? 0 : kbuf;
  101. if(kbuf){
  102. //Backup internal buffer values in external buffer so they can be overwritten
  103. xbuf.move_assign(first+l_build_buf-kbuf, kbuf);
  104. l_merged = op_insertion_sort_step_left(first_block, elements_in_blocks, l_base, comp, move_op());
  105. //Now combine them using the buffer. Elements from buffer can be
  106. //overwritten since they've been saved to xbuf
  107. l_merged = op_merge_left_step_multiple
  108. ( first_block - l_merged, elements_in_blocks, l_merged, l_build_buf, size_type(kbuf - l_merged), comp, move_op());
  109. //Restore internal buffer from external buffer unless kbuf was l_build_buf,
  110. //in that case restoration will happen later
  111. if(kbuf != l_build_buf){
  112. boost::move(xbuf.data()+kbuf-l_merged, xbuf.data() + kbuf, first_block-l_merged+elements_in_blocks);
  113. }
  114. }
  115. else{
  116. l_merged = insertion_sort_step(first_block, elements_in_blocks, l_base, comp);
  117. rotate_gcd(first_block-l_merged, first_block, first_block+elements_in_blocks);
  118. }
  119. //Now combine elements using the buffer. Elements from buffer can't be
  120. //overwritten since xbuf was not big enough, so merge swapping elements.
  121. l_merged = op_merge_left_step_multiple
  122. (first_block-l_merged, elements_in_blocks, l_merged, l_build_buf, size_type(l_build_buf - l_merged), comp, swap_op());
  123. assert(l_merged == l_build_buf);
  124. //////////////////////////////////
  125. // Start of merge to right step
  126. //////////////////////////////////
  127. //If kbuf is l_build_buf then we can merge right without swapping
  128. //Saved data is still in xbuf
  129. if(kbuf && kbuf == l_build_buf){
  130. op_merge_right_step_once(first, elements_in_blocks, l_build_buf, comp, move_op());
  131. //Restore internal buffer from external buffer if kbuf was l_build_buf.
  132. //as this operation was previously delayed.
  133. boost::move(xbuf.data(), xbuf.data() + kbuf, first);
  134. }
  135. else{
  136. op_merge_right_step_once(first, elements_in_blocks, l_build_buf, comp, swap_op());
  137. }
  138. xbuf.clear();
  139. //2*l_build_buf or total already merged
  140. return min_value<size_type>(elements_in_blocks, size_type(2u*l_build_buf));
  141. }
  142. template<class RandItKeys, class KeyCompare, class RandIt, class Compare, class XBuf>
  143. void adaptive_sort_combine_blocks
  144. ( RandItKeys const keys
  145. , KeyCompare key_comp
  146. , RandIt const first
  147. , typename iter_size<RandIt>::type const len
  148. , typename iter_size<RandIt>::type const l_prev_merged
  149. , typename iter_size<RandIt>::type const l_block
  150. , bool const use_buf
  151. , bool const xbuf_used
  152. , XBuf & xbuf
  153. , Compare comp
  154. , bool merge_left)
  155. {
  156. boost::movelib::ignore(xbuf);
  157. typedef typename iter_size<RandIt>::type size_type;
  158. size_type const l_reg_combined = size_type(2u*l_prev_merged);
  159. size_type l_irreg_combined = 0;
  160. size_type const l_total_combined = calculate_total_combined(len, l_prev_merged, &l_irreg_combined);
  161. size_type const n_reg_combined = len/l_reg_combined;
  162. RandIt combined_first = first;
  163. boost::movelib::ignore(l_total_combined);
  164. assert(l_total_combined <= len);
  165. size_type const max_i = size_type(n_reg_combined + (l_irreg_combined != 0));
  166. if(merge_left || !use_buf) {
  167. for( size_type combined_i = 0; combined_i != max_i; ) {
  168. //Now merge blocks
  169. bool const is_last = combined_i==n_reg_combined;
  170. size_type const l_cur_combined = is_last ? l_irreg_combined : l_reg_combined;
  171. range_xbuf<RandIt, size_type, move_op> rbuf( (use_buf && xbuf_used) ? (combined_first-l_block) : combined_first, combined_first);
  172. size_type n_block_a, n_block_b, l_irreg1, l_irreg2;
  173. combine_params( keys, key_comp, l_cur_combined
  174. , l_prev_merged, l_block, rbuf
  175. , n_block_a, n_block_b, l_irreg1, l_irreg2); //Outputs
  176. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A combpar: ", len + l_block);
  177. BOOST_MOVE_ADAPTIVE_SORT_INVARIANT(boost::movelib::is_sorted(combined_first, combined_first + n_block_a*l_block+l_irreg1, comp));
  178. BOOST_MOVE_ADAPTIVE_SORT_INVARIANT(boost::movelib::is_sorted(combined_first + n_block_a*l_block+l_irreg1, combined_first + n_block_a*l_block+l_irreg1+n_block_b*l_block+l_irreg2, comp));
  179. if(!use_buf){
  180. merge_blocks_bufferless
  181. (keys, key_comp, combined_first, l_block, 0u, n_block_a, n_block_b, l_irreg2, comp);
  182. }
  183. else{
  184. merge_blocks_left
  185. (keys, key_comp, combined_first, l_block, 0u, n_block_a, n_block_b, l_irreg2, comp, xbuf_used);
  186. }
  187. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" After merge_blocks_L: ", len + l_block);
  188. ++combined_i;
  189. if(combined_i != max_i)
  190. combined_first += l_reg_combined;
  191. }
  192. }
  193. else{
  194. combined_first += size_type(l_reg_combined*(max_i-1u));
  195. for( size_type combined_i = max_i; combined_i; ) {
  196. --combined_i;
  197. bool const is_last = combined_i==n_reg_combined;
  198. size_type const l_cur_combined = is_last ? l_irreg_combined : l_reg_combined;
  199. RandIt const combined_last(combined_first+l_cur_combined);
  200. range_xbuf<RandIt, size_type, move_op> rbuf(combined_last, xbuf_used ? (combined_last+l_block) : combined_last);
  201. size_type n_block_a, n_block_b, l_irreg1, l_irreg2;
  202. combine_params( keys, key_comp, l_cur_combined
  203. , l_prev_merged, l_block, rbuf
  204. , n_block_a, n_block_b, l_irreg1, l_irreg2); //Outputs
  205. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" A combpar: ", len + l_block);
  206. BOOST_MOVE_ADAPTIVE_SORT_INVARIANT(boost::movelib::is_sorted(combined_first, combined_first + n_block_a*l_block+l_irreg1, comp));
  207. BOOST_MOVE_ADAPTIVE_SORT_INVARIANT(boost::movelib::is_sorted(combined_first + n_block_a*l_block+l_irreg1, combined_first + n_block_a*l_block+l_irreg1+n_block_b*l_block+l_irreg2, comp));
  208. merge_blocks_right
  209. (keys, key_comp, combined_first, l_block, n_block_a, n_block_b, l_irreg2, comp, xbuf_used);
  210. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" After merge_blocks_R: ", len + l_block);
  211. if(combined_i)
  212. combined_first -= l_reg_combined;
  213. }
  214. }
  215. }
  216. //Returns true if buffer is placed in
  217. //[buffer+len-l_intbuf, buffer+len). Otherwise, buffer is
  218. //[buffer,buffer+l_intbuf)
  219. template<class RandIt, class Compare, class XBuf>
  220. bool adaptive_sort_combine_all_blocks
  221. ( RandIt keys
  222. , typename iter_size<RandIt>::type &n_keys
  223. , RandIt const buffer
  224. , typename iter_size<RandIt>::type const l_buf_plus_data
  225. , typename iter_size<RandIt>::type l_merged
  226. , typename iter_size<RandIt>::type &l_intbuf
  227. , XBuf & xbuf
  228. , Compare comp)
  229. {
  230. typedef typename iter_size<RandIt>::type size_type;
  231. RandIt const first = buffer + l_intbuf;
  232. size_type const l_data = size_type(l_buf_plus_data - l_intbuf);
  233. size_type const l_unique = size_type(l_intbuf + n_keys);
  234. //Backup data to external buffer once if possible
  235. bool const common_xbuf = l_data > l_merged && l_intbuf && l_intbuf <= xbuf.capacity();
  236. if(common_xbuf){
  237. xbuf.move_assign(buffer, l_intbuf);
  238. }
  239. bool prev_merge_left = true;
  240. size_type l_prev_total_combined = l_merged, l_prev_block = 0;
  241. bool prev_use_internal_buf = true;
  242. for( size_type n = 0; l_data > l_merged
  243. ; l_merged = size_type(2u*l_merged)
  244. , ++n){
  245. //If l_intbuf is non-zero, use that internal buffer.
  246. // Implies l_block == l_intbuf && use_internal_buf == true
  247. //If l_intbuf is zero, see if half keys can be reused as a reduced emergency buffer,
  248. // Implies l_block == n_keys/2 && use_internal_buf == true
  249. //Otherwise, just give up and and use all keys to merge using rotations (use_internal_buf = false)
  250. bool use_internal_buf = false;
  251. size_type const l_block = lblock_for_combine(l_intbuf, n_keys, size_type(2*l_merged), use_internal_buf);
  252. assert(!l_intbuf || (l_block == l_intbuf));
  253. assert(n == 0 || (!use_internal_buf || prev_use_internal_buf) );
  254. assert(n == 0 || (!use_internal_buf || l_prev_block == l_block) );
  255. bool const is_merge_left = (n&1) == 0;
  256. size_type const l_total_combined = calculate_total_combined(l_data, l_merged);
  257. if(n && prev_use_internal_buf && prev_merge_left){
  258. if(is_merge_left || !use_internal_buf){
  259. move_data_backward(first-l_prev_block, l_prev_total_combined, first, common_xbuf);
  260. }
  261. else{
  262. //Put the buffer just after l_total_combined
  263. RandIt const buf_end = first+l_prev_total_combined;
  264. RandIt const buf_beg = buf_end-l_block;
  265. if(l_prev_total_combined > l_total_combined){
  266. size_type const l_diff = size_type(l_prev_total_combined - l_total_combined);
  267. move_data_backward(buf_beg-l_diff, l_diff, buf_end-l_diff, common_xbuf);
  268. }
  269. else if(l_prev_total_combined < l_total_combined){
  270. size_type const l_diff = size_type(l_total_combined - l_prev_total_combined);
  271. move_data_forward(buf_end, l_diff, buf_beg, common_xbuf);
  272. }
  273. }
  274. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L2(" After move_data : ", l_data + l_intbuf);
  275. }
  276. //Combine to form l_merged*2 segments
  277. if(n_keys){
  278. size_type upper_n_keys_this_iter = size_type(2u*l_merged/l_block);
  279. if(upper_n_keys_this_iter > 256){
  280. adaptive_sort_combine_blocks
  281. ( keys, comp, !use_internal_buf || is_merge_left ? first : first-l_block
  282. , l_data, l_merged, l_block, use_internal_buf, common_xbuf, xbuf, comp, is_merge_left);
  283. }
  284. else{
  285. unsigned char uint_keys[256];
  286. adaptive_sort_combine_blocks
  287. ( uint_keys, less(), !use_internal_buf || is_merge_left ? first : first-l_block
  288. , l_data, l_merged, l_block, use_internal_buf, common_xbuf, xbuf, comp, is_merge_left);
  289. }
  290. }
  291. else{
  292. size_type *const uint_keys = xbuf.template aligned_trailing<size_type>();
  293. adaptive_sort_combine_blocks
  294. ( uint_keys, less(), !use_internal_buf || is_merge_left ? first : first-l_block
  295. , l_data, l_merged, l_block, use_internal_buf, common_xbuf, xbuf, comp, is_merge_left);
  296. }
  297. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(is_merge_left ? " After comb blocks L: " : " After comb blocks R: ", l_data + l_intbuf);
  298. prev_merge_left = is_merge_left;
  299. l_prev_total_combined = l_total_combined;
  300. l_prev_block = l_block;
  301. prev_use_internal_buf = use_internal_buf;
  302. }
  303. assert(l_prev_total_combined == l_data);
  304. bool const buffer_right = prev_use_internal_buf && prev_merge_left;
  305. l_intbuf = prev_use_internal_buf ? l_prev_block : 0u;
  306. n_keys = size_type(l_unique - l_intbuf);
  307. //Restore data from to external common buffer if used
  308. if(common_xbuf){
  309. if(buffer_right){
  310. boost::move(xbuf.data(), xbuf.data() + l_intbuf, buffer+l_data);
  311. }
  312. else{
  313. boost::move(xbuf.data(), xbuf.data() + l_intbuf, buffer);
  314. }
  315. }
  316. return buffer_right;
  317. }
  318. template<class RandIt, class Compare, class XBuf>
  319. void adaptive_sort_final_merge( bool buffer_right
  320. , RandIt const first
  321. , typename iter_size<RandIt>::type const l_intbuf
  322. , typename iter_size<RandIt>::type const n_keys
  323. , typename iter_size<RandIt>::type const len
  324. , XBuf & xbuf
  325. , Compare comp)
  326. {
  327. //assert(n_keys || xbuf.size() == l_intbuf);
  328. xbuf.clear();
  329. typedef typename iter_size<RandIt>::type size_type;
  330. size_type const n_key_plus_buf = size_type(l_intbuf+n_keys);
  331. if(buffer_right){
  332. //Use stable sort as some buffer elements might not be unique (see non_unique_buf)
  333. stable_sort(first+len-l_intbuf, first+len, comp, xbuf);
  334. stable_merge( first+n_keys, first+len-l_intbuf, first+len, antistable<Compare>(comp), xbuf);
  335. unstable_sort(first, first+n_keys, comp, xbuf);
  336. stable_merge(first, first+n_keys, first+len, comp, xbuf);
  337. }
  338. else{
  339. //Use stable sort as some buffer elements might not be unique (see non_unique_buf)
  340. stable_sort(first, first+n_key_plus_buf, comp, xbuf);
  341. if(xbuf.capacity() >= n_key_plus_buf){
  342. buffered_merge(first, first+n_key_plus_buf, first+len, comp, xbuf);
  343. }
  344. else if(xbuf.capacity() >= min_value<size_type>(l_intbuf, n_keys)){
  345. stable_merge( first+n_keys, first+n_key_plus_buf
  346. , first+len, comp, xbuf);
  347. stable_merge(first, first+n_keys, first+len, comp, xbuf);
  348. }
  349. else{
  350. stable_merge(first, first+n_key_plus_buf, first+len, comp, xbuf);
  351. }
  352. }
  353. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" After final_merge : ", len);
  354. }
  355. template<class RandIt, class Compare, class Unsigned, class XBuf>
  356. bool adaptive_sort_build_params
  357. (RandIt first, Unsigned const len, Compare comp
  358. , Unsigned &n_keys, Unsigned &l_intbuf, Unsigned &l_base, Unsigned &l_build_buf
  359. , XBuf & xbuf
  360. )
  361. {
  362. typedef typename iter_size<RandIt>::type size_type;
  363. //Calculate ideal parameters and try to collect needed unique keys
  364. l_base = 0u;
  365. //Try to find a value near sqrt(len) that is 2^N*l_base where
  366. //l_base <= AdaptiveSortInsertionSortThreshold. This property is important
  367. //as build_blocks merges to the left iteratively duplicating the
  368. //merged size and all the buffer must be used just before the final
  369. //merge to right step. This guarantees "build_blocks" produces
  370. //segments of size l_build_buf*2, maximizing the classic merge phase.
  371. l_intbuf = size_type(ceil_sqrt_multiple(len, &l_base));
  372. //The internal buffer can be expanded if there is enough external memory
  373. while(xbuf.capacity() >= l_intbuf*2){
  374. l_intbuf = size_type(2u*l_intbuf);
  375. }
  376. //This is the minimum number of keys to implement the ideal algorithm
  377. //
  378. //l_intbuf is used as buffer plus the key count
  379. size_type n_min_ideal_keys = size_type(l_intbuf-1u);
  380. while(n_min_ideal_keys >= (len-l_intbuf-n_min_ideal_keys)/l_intbuf){
  381. --n_min_ideal_keys;
  382. }
  383. ++n_min_ideal_keys;
  384. assert(n_min_ideal_keys <= l_intbuf);
  385. if(xbuf.template supports_aligned_trailing<size_type>
  386. (l_intbuf, size_type((size_type(len-l_intbuf)-1u)/l_intbuf+1u))){
  387. n_keys = 0u;
  388. l_build_buf = l_intbuf;
  389. }
  390. else{
  391. //Try to achieve a l_build_buf of length l_intbuf*2, so that we can merge with that
  392. //l_intbuf*2 buffer in "build_blocks" and use half of them as buffer and the other half
  393. //as keys in combine_all_blocks. In that case n_keys >= n_min_ideal_keys but by a small margin.
  394. //
  395. //If available memory is 2*sqrt(l), then only sqrt(l) unique keys are needed,
  396. //(to be used for keys in combine_all_blocks) as the whole l_build_buf
  397. //will be backuped in the buffer during build_blocks.
  398. bool const non_unique_buf = xbuf.capacity() >= l_intbuf;
  399. size_type const to_collect = non_unique_buf ? n_min_ideal_keys : size_type(l_intbuf*2u);
  400. size_type collected = collect_unique(first, first+len, to_collect, comp, xbuf);
  401. //If available memory is 2*sqrt(l), then for "build_params"
  402. //the situation is the same as if 2*l_intbuf were collected.
  403. if(non_unique_buf && collected == n_min_ideal_keys){
  404. l_build_buf = l_intbuf;
  405. n_keys = n_min_ideal_keys;
  406. }
  407. else if(collected == 2*l_intbuf){
  408. //l_intbuf*2 elements found. Use all of them in the build phase
  409. l_build_buf = size_type(l_intbuf*2);
  410. n_keys = l_intbuf;
  411. }
  412. else if(collected >= (n_min_ideal_keys+l_intbuf)){
  413. l_build_buf = l_intbuf;
  414. n_keys = size_type(collected - l_intbuf);
  415. }
  416. //If collected keys are not enough, try to fix n_keys and l_intbuf. If no fix
  417. //is possible (due to very low unique keys), then go to a slow sort based on rotations.
  418. else{
  419. assert(collected < (n_min_ideal_keys+l_intbuf));
  420. if(collected < 4){ //No combination possible with less that 4 keys
  421. return false;
  422. }
  423. n_keys = l_intbuf;
  424. while(n_keys & (n_keys-1u)){
  425. n_keys &= size_type(n_keys-1u); // make it power or 2
  426. }
  427. while(n_keys > collected){
  428. n_keys/=2;
  429. }
  430. //AdaptiveSortInsertionSortThreshold is always power of two so the minimum is power of two
  431. l_base = min_value<Unsigned>(n_keys, AdaptiveSortInsertionSortThreshold);
  432. l_intbuf = 0;
  433. l_build_buf = n_keys;
  434. }
  435. assert((n_keys+l_intbuf) >= l_build_buf);
  436. }
  437. return true;
  438. }
  439. // Main explanation of the sort algorithm.
  440. //
  441. // csqrtlen = ceil(sqrt(len));
  442. //
  443. // * First, 2*csqrtlen unique elements elements are extracted from elements to be
  444. // sorted and placed in the beginning of the range.
  445. //
  446. // * Step "build_blocks": In this nearly-classic merge step, 2*csqrtlen unique elements
  447. // will be used as auxiliary memory, so trailing len-2*csqrtlen elements are
  448. // are grouped in blocks of sorted 4*csqrtlen elements. At the end of the step
  449. // 2*csqrtlen unique elements are again the leading elements of the whole range.
  450. //
  451. // * Step "combine_blocks": pairs of previously formed blocks are merged with a different
  452. // ("smart") algorithm to form blocks of 8*csqrtlen elements. This step is slower than the
  453. // "build_blocks" step and repeated iteratively (forming blocks of 16*csqrtlen, 32*csqrtlen
  454. // elements, etc) of until all trailing (len-2*csqrtlen) elements are merged.
  455. //
  456. // In "combine_blocks" len/csqrtlen elements used are as "keys" (markers) to
  457. // know if elements belong to the first or second block to be merged and another
  458. // leading csqrtlen elements are used as buffer. Explanation of the "combine_blocks" step:
  459. //
  460. // Iteratively until all trailing (len-2*csqrtlen) elements are merged:
  461. // Iteratively for each pair of previously merged block:
  462. // * Blocks are divided groups of csqrtlen elements and
  463. // 2*merged_block/csqrtlen keys are sorted to be used as markers
  464. // * Groups are selection-sorted by first or last element (depending whether they are going
  465. // to be merged to left or right) and keys are reordered accordingly as an imitation-buffer.
  466. // * Elements of each block pair are merged using the csqrtlen buffer taking into account
  467. // if they belong to the first half or second half (marked by the key).
  468. //
  469. // * In the final merge step leading elements (2*csqrtlen) are sorted and merged with
  470. // rotations with the rest of sorted elements in the "combine_blocks" step.
  471. //
  472. // Corner cases:
  473. //
  474. // * If no 2*csqrtlen elements can be extracted:
  475. //
  476. // * If csqrtlen+len/csqrtlen are extracted, then only csqrtlen elements are used
  477. // as buffer in the "build_blocks" step forming blocks of 2*csqrtlen elements. This
  478. // means that an additional "combine_blocks" step will be needed to merge all elements.
  479. //
  480. // * If no csqrtlen+len/csqrtlen elements can be extracted, but still more than a minimum,
  481. // then reduces the number of elements used as buffer and keys in the "build_blocks"
  482. // and "combine_blocks" steps. If "combine_blocks" has no enough keys due to this reduction
  483. // then uses a rotation based smart merge.
  484. //
  485. // * If the minimum number of keys can't be extracted, a rotation-based sorting is performed.
  486. //
  487. // * If auxiliary memory is more or equal than ceil(len/2), half-copying mergesort is used.
  488. //
  489. // * If auxiliary memory is more than csqrtlen+n_keys*sizeof(std::size_t),
  490. // then only csqrtlen elements need to be extracted and "combine_blocks" will use integral
  491. // keys to combine blocks.
  492. //
  493. // * If auxiliary memory is available, the "build_blocks" will be extended to build bigger blocks
  494. // using classic merge and "combine_blocks" will use bigger blocks when merging.
  495. template<class RandIt, class Compare, class XBuf>
  496. void adaptive_sort_impl
  497. ( RandIt first
  498. , typename iter_size<RandIt>::type const len
  499. , Compare comp
  500. , XBuf & xbuf
  501. )
  502. {
  503. typedef typename iter_size<RandIt>::type size_type;
  504. //Small sorts go directly to insertion sort
  505. if(len <= size_type(AdaptiveSortInsertionSortThreshold)){
  506. insertion_sort(first, first + len, comp);
  507. }
  508. else if((len-len/2) <= xbuf.capacity()){
  509. merge_sort(first, first+len, comp, xbuf.data());
  510. }
  511. else{
  512. //Make sure it is at least four
  513. BOOST_MOVE_STATIC_ASSERT(AdaptiveSortInsertionSortThreshold >= 4);
  514. size_type l_base = 0;
  515. size_type l_intbuf = 0;
  516. size_type n_keys = 0;
  517. size_type l_build_buf = 0;
  518. //Calculate and extract needed unique elements. If a minimum is not achieved
  519. //fallback to a slow stable sort
  520. if(!adaptive_sort_build_params(first, len, comp, n_keys, l_intbuf, l_base, l_build_buf, xbuf)){
  521. stable_sort(first, first+len, comp, xbuf);
  522. }
  523. else{
  524. assert(l_build_buf);
  525. //Otherwise, continue the adaptive_sort
  526. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1("\n After collect_unique: ", len);
  527. size_type const n_key_plus_buf = size_type(l_intbuf+n_keys);
  528. //l_build_buf is always power of two if l_intbuf is zero
  529. assert(l_intbuf || (0 == (l_build_buf & (l_build_buf-1))));
  530. //Classic merge sort until internal buffer and xbuf are exhausted
  531. size_type const l_merged = adaptive_sort_build_blocks
  532. ( first + n_key_plus_buf-l_build_buf
  533. , size_type(len-n_key_plus_buf+l_build_buf)
  534. , l_base, l_build_buf, xbuf, comp);
  535. BOOST_MOVE_ADAPTIVE_SORT_PRINT_L1(" After build_blocks: ", len);
  536. //Non-trivial merge
  537. bool const buffer_right = adaptive_sort_combine_all_blocks
  538. (first, n_keys, first+n_keys, size_type(len-n_keys), l_merged, l_intbuf, xbuf, comp);
  539. //Sort keys and buffer and merge the whole sequence
  540. adaptive_sort_final_merge(buffer_right, first, l_intbuf, n_keys, len, xbuf, comp);
  541. }
  542. }
  543. }
  544. } //namespace detail_adaptive {
  545. ///@endcond
  546. //! <b>Effects</b>: Sorts the elements in the range [first, last) in ascending order according
  547. //! to comparison functor "comp". The sort is stable (order of equal elements
  548. //! is guaranteed to be preserved). Performance is improved if additional raw storage is
  549. //! provided.
  550. //!
  551. //! <b>Requires</b>:
  552. //! - RandIt must meet the requirements of ValueSwappable and RandomAccessIterator.
  553. //! - The type of dereferenced RandIt must meet the requirements of MoveAssignable and MoveConstructible.
  554. //!
  555. //! <b>Parameters</b>:
  556. //! - first, last: the range of elements to sort
  557. //! - comp: comparison function object which returns true if the first argument is is ordered before the second.
  558. //! - uninitialized, uninitialized_len: raw storage starting on "uninitialized", able to hold "uninitialized_len"
  559. //! elements of type iterator_traits<RandIt>::value_type. Maximum performance is achieved when uninitialized_len
  560. //! is ceil(std::distance(first, last)/2).
  561. //!
  562. //! <b>Throws</b>: If comp throws or the move constructor, move assignment or swap of the type
  563. //! of dereferenced RandIt throws.
  564. //!
  565. //! <b>Complexity</b>: Always K x O(Nxlog(N)) comparisons and move assignments/constructors/swaps.
  566. //! Comparisons are close to minimum even with no additional memory. Constant factor for data movement is minimized
  567. //! when uninitialized_len is ceil(std::distance(first, last)/2). Pretty good enough performance is achieved when
  568. //! ceil(sqrt(std::distance(first, last)))*2.
  569. //!
  570. //! <b>Caution</b>: Experimental implementation, not production-ready.
  571. template<class RandIt, class RandRawIt, class Compare>
  572. void adaptive_sort( RandIt first, RandIt last, Compare comp
  573. , RandRawIt uninitialized
  574. , typename iter_size<RandIt>::type uninitialized_len)
  575. {
  576. typedef typename iter_size<RandIt>::type size_type;
  577. typedef typename iterator_traits<RandIt>::value_type value_type;
  578. ::boost::movelib::adaptive_xbuf<value_type, RandRawIt, size_type> xbuf(uninitialized, uninitialized_len);
  579. ::boost::movelib::detail_adaptive::adaptive_sort_impl(first, size_type(last - first), comp, xbuf);
  580. }
  581. template<class RandIt, class Compare>
  582. void adaptive_sort( RandIt first, RandIt last, Compare comp)
  583. {
  584. typedef typename iterator_traits<RandIt>::value_type value_type;
  585. adaptive_sort(first, last, comp, (value_type*)0, 0u);
  586. }
  587. } //namespace movelib {
  588. } //namespace boost {
  589. #include <boost/move/detail/config_end.hpp>
  590. #if defined(BOOST_CLANG) || (defined(BOOST_GCC) && (BOOST_GCC >= 40600))
  591. #pragma GCC diagnostic pop
  592. #endif
  593. #endif //#define BOOST_MOVE_ADAPTIVE_SORT_HPP