PageRenderTime 28ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/boost/sort/pdqsort/pdqsort.hpp

https://bitbucket.org/bosp/external-boost
C++ Header | 618 lines | 342 code | 92 blank | 184 comment | 104 complexity | 79fb18079014d97f9c2da1c2a10f3516 MD5 | raw file
Possible License(s): MIT
  1. // Pattern-defeating quicksort
  2. // Copyright Orson Peters 2021.
  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. std::size_t limit = 0;
  90. for (Iter cur = begin + 1; cur != end; ++cur) {
  91. Iter sift = cur;
  92. Iter sift_1 = cur - 1;
  93. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  94. if (comp(*sift, *sift_1)) {
  95. T tmp = BOOST_PDQSORT_PREFER_MOVE(*sift);
  96. do { *sift-- = BOOST_PDQSORT_PREFER_MOVE(*sift_1); }
  97. while (sift != begin && comp(tmp, *--sift_1));
  98. *sift = BOOST_PDQSORT_PREFER_MOVE(tmp);
  99. limit += cur - sift;
  100. }
  101. if (limit > partial_insertion_sort_limit) return false;
  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. size_t 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 (size_t 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 (size_t 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. // The following branchless partitioning is derived from "BlockQuicksort: How Branch
  173. // Mispredictions don’t affect Quicksort" by Stefan Edelkamp and Armin Weiss, but
  174. // heavily micro-optimized.
  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. Iter offsets_l_base = first;
  180. Iter offsets_r_base = last;
  181. size_t num_l, num_r, start_l, start_r;
  182. num_l = num_r = start_l = start_r = 0;
  183. while (first < last) {
  184. // Fill up offset blocks with elements that are on the wrong side.
  185. // First we determine how much elements are considered for each offset block.
  186. size_t num_unknown = last - first;
  187. size_t left_split = num_l == 0 ? (num_r == 0 ? num_unknown / 2 : num_unknown) : 0;
  188. size_t right_split = num_r == 0 ? (num_unknown - left_split) : 0;
  189. // Fill the offset blocks.
  190. if (left_split >= block_size) {
  191. for (size_t i = 0; i < block_size;) {
  192. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  193. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  194. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  195. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  196. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  197. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  198. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  199. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  200. }
  201. } else {
  202. for (size_t i = 0; i < left_split;) {
  203. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  204. }
  205. }
  206. if (right_split >= block_size) {
  207. for (size_t i = 0; i < block_size;) {
  208. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  209. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  210. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  211. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  212. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  213. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  214. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  215. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  216. }
  217. } else {
  218. for (size_t i = 0; i < right_split;) {
  219. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  220. }
  221. }
  222. // Swap elements and update block sizes and first/last boundaries.
  223. size_t num = (std::min)(num_l, num_r);
  224. swap_offsets(offsets_l_base, offsets_r_base,
  225. offsets_l + start_l, offsets_r + start_r,
  226. num, num_l == num_r);
  227. num_l -= num; num_r -= num;
  228. start_l += num; start_r += num;
  229. if (num_l == 0) {
  230. start_l = 0;
  231. offsets_l_base = first;
  232. }
  233. if (num_r == 0) {
  234. start_r = 0;
  235. offsets_r_base = last;
  236. }
  237. }
  238. // We have now fully identified [first, last)'s proper position. Swap the last elements.
  239. if (num_l) {
  240. offsets_l += start_l;
  241. while (num_l--) std::iter_swap(offsets_l_base + offsets_l[num_l], --last);
  242. first = last;
  243. }
  244. if (num_r) {
  245. offsets_r += start_r;
  246. while (num_r--) std::iter_swap(offsets_r_base - offsets_r[num_r], first), ++first;
  247. last = first;
  248. }
  249. }
  250. // Put the pivot in the right place.
  251. Iter pivot_pos = first - 1;
  252. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  253. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  254. return std::make_pair(pivot_pos, already_partitioned);
  255. }
  256. // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
  257. // to the pivot are put in the right-hand partition. Returns the position of the pivot after
  258. // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
  259. // pivot is a median of at least 3 elements and that [begin, end) is at least
  260. // insertion_sort_threshold long.
  261. template<class Iter, class Compare>
  262. inline std::pair<Iter, bool> partition_right(Iter begin, Iter end, Compare comp) {
  263. typedef typename std::iterator_traits<Iter>::value_type T;
  264. // Move pivot into local for speed.
  265. T pivot(BOOST_PDQSORT_PREFER_MOVE(*begin));
  266. Iter first = begin;
  267. Iter last = end;
  268. // Find the first element greater than or equal than the pivot (the median of 3 guarantees
  269. // this exists).
  270. while (comp(*++first, pivot));
  271. // Find the first element strictly smaller than the pivot. We have to guard this search if
  272. // there was no element before *first.
  273. if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
  274. else while ( !comp(*--last, pivot));
  275. // If the first pair of elements that should be swapped to partition are the same element,
  276. // the passed in sequence already was correctly partitioned.
  277. bool already_partitioned = first >= last;
  278. // Keep swapping pairs of elements that are on the wrong side of the pivot. Previously
  279. // swapped pairs guard the searches, which is why the first iteration is special-cased
  280. // above.
  281. while (first < last) {
  282. std::iter_swap(first, last);
  283. while (comp(*++first, pivot));
  284. while (!comp(*--last, pivot));
  285. }
  286. // Put the pivot in the right place.
  287. Iter pivot_pos = first - 1;
  288. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  289. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  290. return std::make_pair(pivot_pos, already_partitioned);
  291. }
  292. // Similar function to the one above, except elements equal to the pivot are put to the left of
  293. // the pivot and it doesn't check or return if the passed sequence already was partitioned.
  294. // Since this is rarely used (the many equal case), and in that case pdqsort already has O(n)
  295. // performance, no block quicksort is applied here for simplicity.
  296. template<class Iter, class Compare>
  297. inline Iter partition_left(Iter begin, Iter end, Compare comp) {
  298. typedef typename std::iterator_traits<Iter>::value_type T;
  299. T pivot(BOOST_PDQSORT_PREFER_MOVE(*begin));
  300. Iter first = begin;
  301. Iter last = end;
  302. while (comp(pivot, *--last));
  303. if (last + 1 == end) while (first < last && !comp(pivot, *++first));
  304. else while ( !comp(pivot, *++first));
  305. while (first < last) {
  306. std::iter_swap(first, last);
  307. while (comp(pivot, *--last));
  308. while (!comp(pivot, *++first));
  309. }
  310. Iter pivot_pos = last;
  311. *begin = BOOST_PDQSORT_PREFER_MOVE(*pivot_pos);
  312. *pivot_pos = BOOST_PDQSORT_PREFER_MOVE(pivot);
  313. return pivot_pos;
  314. }
  315. template<class Iter, class Compare, bool Branchless>
  316. inline void pdqsort_loop(Iter begin, Iter end, Compare comp, int bad_allowed, bool leftmost = true) {
  317. typedef typename std::iterator_traits<Iter>::difference_type diff_t;
  318. // Use a while loop for tail recursion elimination.
  319. while (true) {
  320. diff_t size = end - begin;
  321. // Insertion sort is faster for small arrays.
  322. if (size < insertion_sort_threshold) {
  323. if (leftmost) insertion_sort(begin, end, comp);
  324. else unguarded_insertion_sort(begin, end, comp);
  325. return;
  326. }
  327. // Choose pivot as median of 3 or pseudomedian of 9.
  328. diff_t s2 = size / 2;
  329. if (size > ninther_threshold) {
  330. sort3(begin, begin + s2, end - 1, comp);
  331. sort3(begin + 1, begin + (s2 - 1), end - 2, comp);
  332. sort3(begin + 2, begin + (s2 + 1), end - 3, comp);
  333. sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), comp);
  334. std::iter_swap(begin, begin + s2);
  335. } else sort3(begin + s2, begin, end - 1, comp);
  336. // If *(begin - 1) is the end of the right partition of a previous partition operation
  337. // there is no element in [begin, end) that is smaller than *(begin - 1). Then if our
  338. // pivot compares equal to *(begin - 1) we change strategy, putting equal elements in
  339. // the left partition, greater elements in the right partition. We do not have to
  340. // recurse on the left partition, since it's sorted (all equal).
  341. if (!leftmost && !comp(*(begin - 1), *begin)) {
  342. begin = partition_left(begin, end, comp) + 1;
  343. continue;
  344. }
  345. // Partition and get results.
  346. std::pair<Iter, bool> part_result =
  347. Branchless ? partition_right_branchless(begin, end, comp)
  348. : partition_right(begin, end, comp);
  349. Iter pivot_pos = part_result.first;
  350. bool already_partitioned = part_result.second;
  351. // Check for a highly unbalanced partition.
  352. diff_t l_size = pivot_pos - begin;
  353. diff_t r_size = end - (pivot_pos + 1);
  354. bool highly_unbalanced = l_size < size / 8 || r_size < size / 8;
  355. // If we got a highly unbalanced partition we shuffle elements to break many patterns.
  356. if (highly_unbalanced) {
  357. // If we had too many bad partitions, switch to heapsort to guarantee O(n log n).
  358. if (--bad_allowed == 0) {
  359. std::make_heap(begin, end, comp);
  360. std::sort_heap(begin, end, comp);
  361. return;
  362. }
  363. if (l_size >= insertion_sort_threshold) {
  364. std::iter_swap(begin, begin + l_size / 4);
  365. std::iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
  366. if (l_size > ninther_threshold) {
  367. std::iter_swap(begin + 1, begin + (l_size / 4 + 1));
  368. std::iter_swap(begin + 2, begin + (l_size / 4 + 2));
  369. std::iter_swap(pivot_pos - 2, pivot_pos - (l_size / 4 + 1));
  370. std::iter_swap(pivot_pos - 3, pivot_pos - (l_size / 4 + 2));
  371. }
  372. }
  373. if (r_size >= insertion_sort_threshold) {
  374. std::iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
  375. std::iter_swap(end - 1, end - r_size / 4);
  376. if (r_size > ninther_threshold) {
  377. std::iter_swap(pivot_pos + 2, pivot_pos + (2 + r_size / 4));
  378. std::iter_swap(pivot_pos + 3, pivot_pos + (3 + r_size / 4));
  379. std::iter_swap(end - 2, end - (1 + r_size / 4));
  380. std::iter_swap(end - 3, end - (2 + r_size / 4));
  381. }
  382. }
  383. } else {
  384. // If we were decently balanced and we tried to sort an already partitioned
  385. // sequence try to use insertion sort.
  386. if (already_partitioned && partial_insertion_sort(begin, pivot_pos, comp)
  387. && partial_insertion_sort(pivot_pos + 1, end, comp)) return;
  388. }
  389. // Sort the left partition first using recursion and do tail recursion elimination for
  390. // the right-hand partition.
  391. pdqsort_loop<Iter, Compare, Branchless>(begin, pivot_pos, comp, bad_allowed, leftmost);
  392. begin = pivot_pos + 1;
  393. leftmost = false;
  394. }
  395. }
  396. }
  397. /*! \brief Generic sort algorithm using random access iterators and a user-defined comparison operator.
  398. \details @c pdqsort is a fast generic sorting algorithm that is similar in concept to introsort
  399. but runs faster on certain patterns. @c pdqsort is in-place, unstable, deterministic, has a worst
  400. case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>. Even without patterns, the
  401. quicksort has been very efficiently implemented, and @c pdqsort runs 1-5% faster than GCC 6.2's
  402. @c std::sort. If the type being sorted is @c std::is_arithmetic and Compare is @c std::less or
  403. @c std::greater this function will automatically use @c pdqsort_branchless for far greater speedups.
  404. \param[in] first Iterator pointer to first element.
  405. \param[in] last Iterator pointing to one beyond the end of data.
  406. \param[in] comp A binary functor that returns whether the first element passed to it should go before the second in order.
  407. \pre [@c first, @c last) is a valid range.
  408. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  409. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  410. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  411. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  412. \return @c void.
  413. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  414. (or moves), functors, or any operations on iterators throw.
  415. \warning Invalid arguments cause undefined behaviour.
  416. \warning Throwing an exception may cause data loss.
  417. */
  418. template<class Iter, class Compare>
  419. inline void pdqsort(Iter first, Iter last, Compare comp) {
  420. if (first == last) return;
  421. pdqsort_detail::pdqsort_loop<Iter, Compare,
  422. pdqsort_detail::is_default_compare<typename boost::decay<Compare>::type>::value &&
  423. boost::is_arithmetic<typename std::iterator_traits<Iter>::value_type>::value>(
  424. first, last, comp, pdqsort_detail::log2(last - first));
  425. }
  426. /*! \brief Generic sort algorithm using random access iterators and a user-defined comparison operator.
  427. \details @c pdqsort_branchless is a fast generic sorting algorithm that is similar in concept to
  428. introsort but runs faster on certain patterns. @c pdqsort_branchless is in-place, unstable,
  429. deterministic, has a worst case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>.
  430. Even without patterns, the quicksort has been very efficiently implemented with block based
  431. partitioning, and @c pdqsort_branchless runs 80-90% faster than GCC 6.2's @c std::sort when sorting
  432. small data such as integers. However, this speedup is gained by totally bypassing the branch
  433. predictor, if your comparison operator or iterator contains branches you will most likely see little
  434. gain or a small loss in performance.
  435. \param[in] first Iterator pointer to first element.
  436. \param[in] last Iterator pointing to one beyond the end of data.
  437. \param[in] comp A binary functor that returns whether the first element passed to it should go before the second in order.
  438. \pre [@c first, @c last) is a valid range.
  439. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  440. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  441. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  442. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  443. \return @c void.
  444. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  445. (or moves), functors, or any operations on iterators throw.
  446. \warning Invalid arguments cause undefined behaviour.
  447. \warning Throwing an exception may cause data loss.
  448. */
  449. template<class Iter, class Compare>
  450. inline void pdqsort_branchless(Iter first, Iter last, Compare comp) {
  451. if (first == last) return;
  452. pdqsort_detail::pdqsort_loop<Iter, Compare, true>(
  453. first, last, comp, pdqsort_detail::log2(last - first));
  454. }
  455. /*! \brief Generic sort algorithm using random access iterators.
  456. \details @c pdqsort is a fast generic sorting algorithm that is similar in concept to introsort
  457. but runs faster on certain patterns. @c pdqsort is in-place, unstable, deterministic, has a worst
  458. case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>. Even without patterns, the
  459. quicksort partitioning has been very efficiently implemented, and @c pdqsort runs 80-90% faster than
  460. GCC 6.2's @c std::sort. If the type being sorted is @c std::is_arithmetic this function will
  461. automatically use @c pdqsort_branchless.
  462. \param[in] first Iterator pointer to first element.
  463. \param[in] last Iterator pointing to one beyond the end of data.
  464. \pre [@c first, @c last) is a valid range.
  465. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  466. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  467. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  468. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  469. \return @c void.
  470. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  471. (or moves), functors, or any operations on iterators throw.
  472. \warning Invalid arguments cause undefined behaviour.
  473. \warning Throwing an exception may cause data loss.
  474. */
  475. template<class Iter>
  476. inline void pdqsort(Iter first, Iter last) {
  477. typedef typename std::iterator_traits<Iter>::value_type T;
  478. pdqsort(first, last, std::less<T>());
  479. }
  480. /*! \brief Generic sort algorithm using random access iterators.
  481. \details @c pdqsort_branchless is a fast generic sorting algorithm that is similar in concept to
  482. introsort but runs faster on certain patterns. @c pdqsort_branchless is in-place, unstable,
  483. deterministic, has a worst case runtime of <em>O(N * lg(N))</em> and a best case of <em>O(N)</em>.
  484. Even without patterns, the quicksort has been very efficiently implemented with block based
  485. partitioning, and @c pdqsort_branchless runs 80-90% faster than GCC 6.2's @c std::sort when sorting
  486. small data such as integers. However, this speedup is gained by totally bypassing the branch
  487. predictor, if your comparison operator or iterator contains branches you will most likely see little
  488. gain or a small loss in performance.
  489. \param[in] first Iterator pointer to first element.
  490. \param[in] last Iterator pointing to one beyond the end of data.
  491. \pre [@c first, @c last) is a valid range.
  492. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveAssignable">MoveAssignable</a>
  493. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/MoveConstructible">MoveConstructible</a>
  494. \pre @c RandomAccessIter @c value_type is <a href="http://en.cppreference.com/w/cpp/concept/LessThanComparable">LessThanComparable</a>
  495. \post The elements in the range [@c first, @c last) are sorted in ascending order.
  496. \return @c void.
  497. \throws std::exception Propagates exceptions if any of the element comparisons, the element swaps
  498. (or moves), functors, or any operations on iterators throw.
  499. \warning Invalid arguments cause undefined behaviour.
  500. \warning Throwing an exception may cause data loss.
  501. */
  502. template<class Iter>
  503. inline void pdqsort_branchless(Iter first, Iter last) {
  504. typedef typename std::iterator_traits<Iter>::value_type T;
  505. pdqsort_branchless(first, last, std::less<T>());
  506. }
  507. }
  508. }
  509. #undef BOOST_PDQSORT_PREFER_MOVE
  510. #endif