pdqsort.hpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. // Pattern-defeating quicksort
  2. // Copyright Orson Peters 2017.
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // See http://www.boost.org/libs/sort/ for library home page.
  7. #ifndef BOOST_SORT_PDQSORT_HPP
  8. #define BOOST_SORT_PDQSORT_HPP
  9. #include <algorithm>
  10. #include <cstddef>
  11. #include <functional>
  12. #include <iterator>
  13. #include <utility>
  14. #include <boost/type_traits.hpp>
  15. #if __cplusplus >= 201103L
  16. #include <cstdint>
  17. #define BOOST_PDQSORT_PREFER_MOVE(x) std::move(x)
  18. #else
  19. #define BOOST_PDQSORT_PREFER_MOVE(x) (x)
  20. #endif
  21. namespace boost {
  22. namespace sort {
  23. namespace pdqsort_detail {
  24. enum {
  25. // Partitions below this size are sorted using insertion sort.
  26. insertion_sort_threshold = 24,
  27. // Partitions above this size use Tukey's ninther to select the pivot.
  28. ninther_threshold = 128,
  29. // When we detect an already sorted partition, attempt an insertion sort that allows this
  30. // amount of element moves before giving up.
  31. partial_insertion_sort_limit = 8,
  32. // Must be multiple of 8 due to loop unrolling, and < 256 to fit in unsigned char.
  33. block_size = 64,
  34. // Cacheline size, assumes power of two.
  35. cacheline_size = 64
  36. };
  37. template<class T> struct is_default_compare : boost::false_type { };
  38. template<class T> struct is_default_compare<std::less<T> > : boost::true_type { };
  39. template<class T> struct is_default_compare<std::greater<T> > : boost::true_type { };
  40. // Returns floor(log2(n)), assumes n > 0.
  41. template<class T>
  42. inline int log2(T n) {
  43. int log = 0;
  44. while (n >>= 1) ++log;
  45. return log;
  46. }
  47. // Sorts [begin, end) using insertion sort with the given comparison function.
  48. template<class Iter, class Compare>
  49. inline void insertion_sort(Iter begin, Iter end, Compare comp) {
  50. typedef typename std::iterator_traits<Iter>::value_type T;
  51. if (begin == end) return;
  52. for (Iter cur = begin + 1; cur != end; ++cur) {
  53. Iter sift = cur;
  54. Iter sift_1 = cur - 1;
  55. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  56. if (comp(*sift, *sift_1)) {
  57. T tmp = BOOST_PDQSORT_PREFER_MOVE(*sift);
  58. do { *sift-- = BOOST_PDQSORT_PREFER_MOVE(*sift_1); }
  59. while (sift != begin && comp(tmp, *--sift_1));
  60. *sift = BOOST_PDQSORT_PREFER_MOVE(tmp);
  61. }
  62. }
  63. }
  64. // Sorts [begin, end) using insertion sort with the given comparison function. Assumes
  65. // *(begin - 1) is an element smaller than or equal to any element in [begin, end).
  66. template<class Iter, class Compare>
  67. inline void unguarded_insertion_sort(Iter begin, Iter end, Compare comp) {
  68. typedef typename std::iterator_traits<Iter>::value_type T;
  69. if (begin == end) return;
  70. for (Iter cur = begin + 1; cur != end; ++cur) {
  71. Iter sift = cur;
  72. Iter sift_1 = cur - 1;
  73. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  74. if (comp(*sift, *sift_1)) {
  75. T tmp = BOOST_PDQSORT_PREFER_MOVE(*sift);
  76. do { *sift-- = BOOST_PDQSORT_PREFER_MOVE(*sift_1); }
  77. while (comp(tmp, *--sift_1));
  78. *sift = BOOST_PDQSORT_PREFER_MOVE(tmp);
  79. }
  80. }
  81. }
  82. // Attempts to use insertion sort on [begin, end). Will return false if more than
  83. // partial_insertion_sort_limit elements were moved, and abort sorting. Otherwise it will
  84. // successfully sort and return true.
  85. template<class Iter, class Compare>
  86. inline bool partial_insertion_sort(Iter begin, Iter end, Compare comp) {
  87. typedef typename std::iterator_traits<Iter>::value_type T;
  88. if (begin == end) return true;
  89. int limit = 0;
  90. for (Iter cur = begin + 1; cur != end; ++cur) {
  91. if (limit > partial_insertion_sort_limit) return false;
  92. Iter sift = cur;
  93. Iter sift_1 = cur - 1;
  94. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  95. if (comp(*sift, *sift_1)) {
  96. T tmp = BOOST_PDQSORT_PREFER_MOVE(*sift);
  97. do { *sift-- = BOOST_PDQSORT_PREFER_MOVE(*sift_1); }
  98. while (sift != begin && comp(tmp, *--sift_1));
  99. *sift = BOOST_PDQSORT_PREFER_MOVE(tmp);
  100. limit += cur - sift;
  101. }
  102. }
  103. return true;
  104. }
  105. template<class Iter, class Compare>
  106. inline void sort2(Iter a, Iter b, Compare comp) {
  107. if (comp(*b, *a)) std::iter_swap(a, b);
  108. }
  109. // Sorts the elements *a, *b and *c using comparison function comp.
  110. template<class Iter, class Compare>
  111. inline void sort3(Iter a, Iter b, Iter c, Compare comp) {
  112. sort2(a, b, comp);
  113. sort2(b, c, comp);
  114. sort2(a, b, comp);
  115. }
  116. template<class T>
  117. inline T* align_cacheline(T* p) {
  118. #if defined(UINTPTR_MAX) && __cplusplus >= 201103L
  119. std::uintptr_t ip = reinterpret_cast<std::uintptr_t>(p);
  120. #else
  121. std::size_t ip = reinterpret_cast<std::size_t>(p);
  122. #endif
  123. ip = (ip + cacheline_size - 1) & -cacheline_size;
  124. return reinterpret_cast<T*>(ip);
  125. }
  126. template<class Iter>
  127. inline void swap_offsets(Iter first, Iter last,
  128. unsigned char* offsets_l, unsigned char* offsets_r,
  129. int num, bool use_swaps) {
  130. typedef typename std::iterator_traits<Iter>::value_type T;
  131. if (use_swaps) {
  132. // This case is needed for the descending distribution, where we need
  133. // to have proper swapping for pdqsort to remain O(n).
  134. for (int i = 0; i < num; ++i) {
  135. std::iter_swap(first + offsets_l[i], last - offsets_r[i]);
  136. }
  137. } else if (num > 0) {
  138. Iter l = first + offsets_l[0]; Iter r = last - offsets_r[0];
  139. T tmp(BOOST_PDQSORT_PREFER_MOVE(*l)); *l = BOOST_PDQSORT_PREFER_MOVE(*r);
  140. for (int i = 1; i < num; ++i) {
  141. l = first + offsets_l[i]; *r = BOOST_PDQSORT_PREFER_MOVE(*l);
  142. r = last - offsets_r[i]; *l = BOOST_PDQSORT_PREFER_MOVE(*r);
  143. }
  144. *r = BOOST_PDQSORT_PREFER_MOVE(tmp);
  145. }
  146. }
  147. // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
  148. // to the pivot are put in the right-hand partition. Returns the position of the pivot after
  149. // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
  150. // pivot is a median of at least 3 elements and that [begin, end) is at least
  151. // insertion_sort_threshold long. Uses branchless partitioning.
  152. template<class Iter, class Compare>
  153. inline std::pair<Iter, bool> partition_right_branchless(Iter begin, Iter end, Compare comp) {
  154. typedef typename std::iterator_traits<Iter>::value_type T;
  155. // Move pivot into local for speed.
  156. T pivot(BOOST_PDQSORT_PREFER_MOVE(*begin));
  157. Iter first = begin;
  158. Iter last = end;
  159. // Find the first element greater than or equal than the pivot (the median of 3 guarantees
  160. // this exists).
  161. while (comp(*++first, pivot));
  162. // Find the first element strictly smaller than the pivot. We have to guard this search if
  163. // there was no element before *first.
  164. if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
  165. else while ( !comp(*--last, pivot));
  166. // If the first pair of elements that should be swapped to partition are the same element,
  167. // the passed in sequence already was correctly partitioned.
  168. bool already_partitioned = first >= last;
  169. if (!already_partitioned) {
  170. std::iter_swap(first, last);
  171. ++first;
  172. }
  173. // The following branchless partitioning is derived from "BlockQuicksort: How Branch
  174. // Mispredictions don't affect Quicksort" by Stefan Edelkamp and Armin Weiss.
  175. unsigned char offsets_l_storage[block_size + cacheline_size];
  176. unsigned char offsets_r_storage[block_size + cacheline_size];
  177. unsigned char* offsets_l = align_cacheline(offsets_l_storage);
  178. unsigned char* offsets_r = align_cacheline(offsets_r_storage);
  179. int num_l, num_r, start_l, start_r;
  180. num_l = num_r = start_l = start_r = 0;
  181. while (last - first > 2 * block_size) {
  182. // Fill up offset blocks with elements that are on the wrong side.
  183. if (num_l == 0) {
  184. start_l = 0;
  185. Iter it = first;
  186. for (unsigned char i = 0; i < block_size;) {
  187. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  188. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  189. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  190. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  191. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  192. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  193. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  194. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  195. }
  196. }
  197. if (num_r == 0) {
  198. start_r = 0;
  199. Iter it = last;
  200. for (unsigned char i = 0; i < block_size;) {
  201. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  202. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  203. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  204. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  205. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  206. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  207. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  208. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  209. }
  210. }
  211. // Swap elements and update block sizes and first/last boundaries.
  212. int num = (std::min)(num_l, num_r);
  213. swap_offsets(first, last, offsets_l + start_l, offsets_r + start_r,
  214. num, num_l == num_r);
  215. num_l -= num; num_r -= num;
  216. start_l += num; start_r += num;
  217. if (num_l == 0) first += block_size;
  218. if (num_r == 0) last -= block_size;
  219. }
  220. int l_size = 0, r_size = 0;
  221. int unknown_left = (last - first) - ((num_r || num_l) ? block_size : 0);
  222. if (num_r) {
  223. // Handle leftover block by assigning the unknown elements to the other block.
  224. l_size = unknown_left;
  225. r_size = block_size;
  226. } else if (num_l) {
  227. l_size = block_size;
  228. r_size = unknown_left;
  229. } else {
  230. // No leftover block, split the unknown elements in two blocks.
  231. l_size = unknown_left/2;
  232. r_size = unknown_left - l_size;
  233. }
  234. // Fill offset buffers if needed.
  235. if (unknown_left && !num_l) {
  236. start_l = 0;
  237. Iter it = first;
  238. for (unsigned char i = 0; i < l_size;) {
  239. offsets_l[num_l] = i++; num_l += !comp(*it, pivot); ++it;
  240. }
  241. }
  242. if (unknown_left && !num_r) {
  243. start_r = 0;
  244. Iter it = last;
  245. for (unsigned char i = 0; i < r_size;) {
  246. offsets_r[num_r] = ++i; num_r += comp(*--it, pivot);
  247. }
  248. }
  249. int num = (std::min)(num_l, num_r);
  250. swap_offsets(first, last, offsets_l + start_l, offsets_r + start_r, num, num_l == num_r);
  251. num_l -= num; num_r -= num;
  252. start_l += num; start_r += num;
  253. if (num_l == 0) first += l_size;
  254. if (num_r == 0) last -= r_size;
  255. // We have now fully identified [first, last)'s proper position. Swap the last elements.
  256. if (num_l) {
  257. offsets_l += start_l;
  258. while (num_l--) std::iter_swap(first + offsets_l[num_l], --last);
  259. first = last;
  260. }
  261. if (num_r) {
  262. offsets_r += start_r;
  263. while (num_r--) std::iter_swap(last - offsets_r[num_r], first), ++first;
  264. last = first;
  265. }
  266. // Put the pivot in the right place.
  267. Iter pivot_pos = first - 1;
  268. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  269. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  270. return std::make_pair(pivot_pos, already_partitioned);
  271. }
  272. // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
  273. // to the pivot are put in the right-hand partition. Returns the position of the pivot after
  274. // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
  275. // pivot is a median of at least 3 elements and that [begin, end) is at least
  276. // insertion_sort_threshold long.
  277. template<class Iter, class Compare>
  278. inline std::pair<Iter, bool> partition_right(Iter begin, Iter end, Compare comp) {
  279. typedef typename std::iterator_traits<Iter>::value_type T;
  280. // Move pivot into local for speed.
  281. T pivot(BOOST_PDQSORT_PREFER_MOVE(*begin));
  282. Iter first = begin;
  283. Iter last = end;
  284. // Find the first element greater than or equal than the pivot (the median of 3 guarantees
  285. // this exists).
  286. while (comp(*++first, pivot));
  287. // Find the first element strictly smaller than the pivot. We have to guard this search if
  288. // there was no element before *first.
  289. if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
  290. else while ( !comp(*--last, pivot));
  291. // If the first pair of elements that should be swapped to partition are the same element,
  292. // the passed in sequence already was correctly partitioned.
  293. bool already_partitioned = first >= last;
  294. // Keep swapping pairs of elements that are on the wrong side of the pivot. Previously
  295. // swapped pairs guard the searches, which is why the first iteration is special-cased
  296. // above.
  297. while (first < last) {
  298. std::iter_swap(first, last);
  299. while (comp(*++first, pivot));
  300. while (!comp(*--last, pivot));
  301. }
  302. // Put the pivot in the right place.
  303. Iter pivot_pos = first - 1;
  304. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  305. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  306. return std::make_pair(pivot_pos, already_partitioned);
  307. }
  308. // Similar function to the one above, except elements equal to the pivot are put to the left of
  309. // the pivot and it doesn't check or return if the passed sequence already was partitioned.
  310. // Since this is rarely used (the many equal case), and in that case pdqsort already has O(n)
  311. // performance, no block quicksort is applied here for simplicity.
  312. template<class Iter, class Compare>
  313. inline Iter partition_left(Iter begin, Iter end, Compare comp) {
  314. typedef typename std::iterator_traits<Iter>::value_type T;
  315. T pivot(BOOST_PDQSORT_PREFER_MOVE(*begin));
  316. Iter first = begin;
  317. Iter last = end;
  318. while (comp(pivot, *--last));
  319. if (last + 1 == end) while (first < last && !comp(pivot, *++first));
  320. else while ( !comp(pivot, *++first));
  321. while (first < last) {
  322. std::iter_swap(first, last);
  323. while (comp(pivot, *--last));
  324. while (!comp(pivot, *++first));
  325. }
  326. Iter pivot_pos = last;
  327. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  328. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  329. return pivot_pos;
  330. }
  331. template<class Iter, class Compare, bool Branchless>
  332. inline void pdqsort_loop(Iter begin, Iter end, Compare comp, int bad_allowed, bool leftmost = true) {
  333. typedef typename std::iterator_traits<Iter>::difference_type diff_t;
  334. // Use a while loop for tail recursion elimination.
  335. while (true) {
  336. diff_t size = end - begin;
  337. // Insertion sort is faster for small arrays.
  338. if (size < insertion_sort_threshold) {
  339. if (leftmost) insertion_sort(begin, end, comp);
  340. else unguarded_insertion_sort(begin, end, comp);
  341. return;
  342. }
  343. // Choose pivot as median of 3 or pseudomedian of 9.
  344. diff_t s2 = size / 2;
  345. if (size > ninther_threshold) {
  346. sort3(begin, begin + s2, end - 1, comp);
  347. sort3(begin + 1, begin + (s2 - 1), end - 2, comp);
  348. sort3(begin + 2, begin + (s2 + 1), end - 3, comp);
  349. sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), comp);
  350. std::iter_swap(begin, begin + s2);
  351. } else sort3(begin + s2, begin, end - 1, comp);
  352. // If *(begin - 1) is the end of the right partition of a previous partition operation
  353. // there is no element in [begin, end) that is smaller than *(begin - 1). Then if our
  354. // pivot compares equal to *(begin - 1) we change strategy, putting equal elements in
  355. // the left partition, greater elements in the right partition. We do not have to
  356. // recurse on the left partition, since it's sorted (all equal).
  357. if (!leftmost && !comp(*(begin - 1), *begin)) {
  358. begin = partition_left(begin, end, comp) + 1;
  359. continue;
  360. }
  361. // Partition and get results.
  362. std::pair<Iter, bool> part_result =
  363. Branchless ? partition_right_branchless(begin, end, comp)
  364. : partition_right(begin, end, comp);
  365. Iter pivot_pos = part_result.first;
  366. bool already_partitioned = part_result.second;
  367. // Check for a highly unbalanced partition.
  368. diff_t l_size = pivot_pos - begin;
  369. diff_t r_size = end - (pivot_pos + 1);
  370. bool highly_unbalanced = l_size < size / 8 || r_size < size / 8;
  371. // If we got a highly unbalanced partition we shuffle elements to break many patterns.
  372. if (highly_unbalanced) {
  373. // If we had too many bad partitions, switch to heapsort to guarantee O(n log n).
  374. if (--bad_allowed == 0) {
  375. std::make_heap(begin, end, comp);
  376. std::sort_heap(begin, end, comp);
  377. return;
  378. }
  379. if (l_size >= insertion_sort_threshold) {
  380. std::iter_swap(begin, begin + l_size / 4);
  381. std::iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
  382. if (l_size > ninther_threshold) {
  383. std::iter_swap(begin + 1, begin + (l_size / 4 + 1));
  384. std::iter_swap(begin + 2, begin + (l_size / 4 + 2));
  385. std::iter_swap(pivot_pos - 2, pivot_pos - (l_size / 4 + 1));
  386. std::iter_swap(pivot_pos - 3, pivot_pos - (l_size / 4 + 2));
  387. }
  388. }
  389. if (r_size >= insertion_sort_threshold) {
  390. std::iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
  391. std::iter_swap(end - 1, end - r_size / 4);
  392. if (r_size > ninther_threshold) {
  393. std::iter_swap(pivot_pos + 2, pivot_pos + (2 + r_size / 4));
  394. std::iter_swap(pivot_pos + 3, pivot_pos + (3 + r_size / 4));
  395. std::iter_swap(end - 2, end - (1 + r_size / 4));
  396. std::iter_swap(end - 3, end - (2 + r_size / 4));
  397. }
  398. }
  399. } else {
  400. // If we were decently balanced and we tried to sort an already partitioned
  401. // sequence try to use insertion sort.
  402. if (already_partitioned && partial_insertion_sort(begin, pivot_pos, comp)
  403. && partial_insertion_sort(pivot_pos + 1, end, comp)) return;
  404. }
  405. // Sort the left partition first using recursion and do tail recursion elimination for
  406. // the right-hand partition.
  407. pdqsort_loop<Iter, Compare, Branchless>(begin, pivot_pos, comp, bad_allowed, leftmost);
  408. begin = pivot_pos + 1;
  409. leftmost = false;
  410. }
  411. }
  412. }
  413. /*! \brief Generic sort algorithm using random access iterators and a user-defined comparison operator.
  414. \details @c pdqsort is a fast generic sorting algorithm that is similar in concept to introsort
  415. but runs faster on certain patterns. @c pdqsort is in-place, unstable, deterministic, has a worst
  416. case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>. Even without patterns, the
  417. quicksort has been very efficiently implemented, and @c pdqsort runs 1-5% faster than GCC 6.2's
  418. @c std::sort. If the type being sorted is @c std::is_arithmetic and Compare is @c std::less or
  419. @c std::greater this function will automatically use @c pdqsort_branchless for far greater speedups.
  420. \param[in] first Iterator pointer to first element.
  421. \param[in] last Iterator pointing to one beyond the end of data.
  422. \param[in] comp A binary functor that returns whether the first element passed to it should go before the second in order.
  423. \pre [@c first, @c last) is a valid range.
  424. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  425. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  426. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  427. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  428. \return @c void.
  429. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  430. (or moves), functors, or any operations on iterators throw.
  431. \warning Invalid arguments cause undefined behaviour.
  432. \warning Throwing an exception may cause data loss.
  433. */
  434. template<class Iter, class Compare>
  435. inline void pdqsort(Iter first, Iter last, Compare comp) {
  436. if (first == last) return;
  437. pdqsort_detail::pdqsort_loop<Iter, Compare,
  438. pdqsort_detail::is_default_compare<typename boost::decay<Compare>::type>::value &&
  439. boost::is_arithmetic<typename std::iterator_traits<Iter>::value_type>::value>(
  440. first, last, comp, pdqsort_detail::log2(last - first));
  441. }
  442. /*! \brief Generic sort algorithm using random access iterators and a user-defined comparison operator.
  443. \details @c pdqsort_branchless is a fast generic sorting algorithm that is similar in concept to
  444. introsort but runs faster on certain patterns. @c pdqsort_branchless is in-place, unstable,
  445. deterministic, has a worst case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>.
  446. Even without patterns, the quicksort has been very efficiently implemented with block based
  447. partitioning, and @c pdqsort_branchless runs 80-90% faster than GCC 6.2's @c std::sort when sorting
  448. small data such as integers. However, this speedup is gained by totally bypassing the branch
  449. predictor, if your comparison operator or iterator contains branches you will most likely see little
  450. gain or a small loss in performance.
  451. \param[in] first Iterator pointer to first element.
  452. \param[in] last Iterator pointing to one beyond the end of data.
  453. \param[in] comp A binary functor that returns whether the first element passed to it should go before the second in order.
  454. \pre [@c first, @c last) is a valid range.
  455. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  456. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  457. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  458. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  459. \return @c void.
  460. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  461. (or moves), functors, or any operations on iterators throw.
  462. \warning Invalid arguments cause undefined behaviour.
  463. \warning Throwing an exception may cause data loss.
  464. */
  465. template<class Iter, class Compare>
  466. inline void pdqsort_branchless(Iter first, Iter last, Compare comp) {
  467. if (first == last) return;
  468. pdqsort_detail::pdqsort_loop<Iter, Compare, true>(
  469. first, last, comp, pdqsort_detail::log2(last - first));
  470. }
  471. /*! \brief Generic sort algorithm using random access iterators.
  472. \details @c pdqsort is a fast generic sorting algorithm that is similar in concept to introsort
  473. but runs faster on certain patterns. @c pdqsort is in-place, unstable, deterministic, has a worst
  474. case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>. Even without patterns, the
  475. quicksort partitioning has been very efficiently implemented, and @c pdqsort runs 80-90% faster than
  476. GCC 6.2's @c std::sort. If the type being sorted is @c std::is_arithmetic this function will
  477. automatically use @c pdqsort_branchless.
  478. \param[in] first Iterator pointer to first element.
  479. \param[in] last Iterator pointing to one beyond the end of data.
  480. \pre [@c first, @c last) is a valid range.
  481. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  482. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  483. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  484. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  485. \return @c void.
  486. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  487. (or moves), functors, or any operations on iterators throw.
  488. \warning Invalid arguments cause undefined behaviour.
  489. \warning Throwing an exception may cause data loss.
  490. */
  491. template<class Iter>
  492. inline void pdqsort(Iter first, Iter last) {
  493. typedef typename std::iterator_traits<Iter>::value_type T;
  494. pdqsort(first, last, std::less<T>());
  495. }
  496. /*! \brief Generic sort algorithm using random access iterators.
  497. \details @c pdqsort_branchless is a fast generic sorting algorithm that is similar in concept to
  498. introsort but runs faster on certain patterns. @c pdqsort_branchless is in-place, unstable,
  499. deterministic, has a worst case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>.
  500. Even without patterns, the quicksort has been very efficiently implemented with block based
  501. partitioning, and @c pdqsort_branchless runs 80-90% faster than GCC 6.2's @c std::sort when sorting
  502. small data such as integers. However, this speedup is gained by totally bypassing the branch
  503. predictor, if your comparison operator or iterator contains branches you will most likely see little
  504. gain or a small loss in performance.
  505. \param[in] first Iterator pointer to first element.
  506. \param[in] last Iterator pointing to one beyond the end of data.
  507. \pre [@c first, @c last) is a valid range.
  508. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  509. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  510. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  511. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  512. \return @c void.
  513. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  514. (or moves), functors, or any operations on iterators throw.
  515. \warning Invalid arguments cause undefined behaviour.
  516. \warning Throwing an exception may cause data loss.
  517. */
  518. template<class Iter>
  519. inline void pdqsort_branchless(Iter first, Iter last) {
  520. typedef typename std::iterator_traits<Iter>::value_type T;
  521. pdqsort_branchless(first, last, std::less<T>());
  522. }
  523. }
  524. }
  525. #undef BOOST_PDQSORT_PREFER_MOVE
  526. #endif