pdqsort.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /*
  2. pdqsort.h - Pattern-defeating quicksort.
  3. Copyright (c) 2021 Orson Peters
  4. This software is provided 'as-is', without any express or implied warranty. In no event will the
  5. authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose, including commercial
  7. applications, and to alter it and redistribute it freely, subject to the following restrictions:
  8. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
  9. original software. If you use this software in a product, an acknowledgment in the product
  10. documentation would be appreciated but is not required.
  11. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
  12. being the original software.
  13. 3. This notice may not be removed or altered from any source distribution.
  14. */
  15. #ifndef PDQSORT_H
  16. #define PDQSORT_H
  17. #include <algorithm>
  18. #include <cstddef>
  19. #include <functional>
  20. #include <utility>
  21. #include <iterator>
  22. #if __cplusplus >= 201103L
  23. #include <cstdint>
  24. #include <type_traits>
  25. #define PDQSORT_PREFER_MOVE(x) std::move(x)
  26. #else
  27. #define PDQSORT_PREFER_MOVE(x) (x)
  28. #endif
  29. namespace pdqsort_detail {
  30. enum {
  31. // Partitions below this size are sorted using insertion sort.
  32. insertion_sort_threshold = 24,
  33. // Partitions above this size use Tukey's ninther to select the pivot.
  34. ninther_threshold = 128,
  35. // When we detect an already sorted partition, attempt an insertion sort that allows this
  36. // amount of element moves before giving up.
  37. partial_insertion_sort_limit = 8,
  38. // Must be multiple of 8 due to loop unrolling, and < 256 to fit in unsigned char.
  39. block_size = 64,
  40. // Cacheline size, assumes power of two.
  41. cacheline_size = 64
  42. };
  43. #if __cplusplus >= 201103L
  44. template<class T> struct is_default_compare : std::false_type { };
  45. template<class T> struct is_default_compare<std::less<T>> : std::true_type { };
  46. template<class T> struct is_default_compare<std::greater<T>> : std::true_type { };
  47. #endif
  48. // Returns floor(log2(n)), assumes n > 0.
  49. template<class T>
  50. inline int log2(T n) {
  51. int log = 0;
  52. while (n >>= 1) ++log;
  53. return log;
  54. }
  55. // Sorts [begin, end) using insertion sort with the given comparison function.
  56. template<class Iter, class Compare>
  57. inline void insertion_sort(Iter begin, Iter end, Compare comp) {
  58. typedef typename std::iterator_traits<Iter>::value_type T;
  59. if (begin == end) return;
  60. for (Iter cur = begin + 1; cur != end; ++cur) {
  61. Iter sift = cur;
  62. Iter sift_1 = cur - 1;
  63. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  64. if (comp(*sift, *sift_1)) {
  65. T tmp = PDQSORT_PREFER_MOVE(*sift);
  66. do { *sift-- = PDQSORT_PREFER_MOVE(*sift_1); }
  67. while (sift != begin && comp(tmp, *--sift_1));
  68. *sift = PDQSORT_PREFER_MOVE(tmp);
  69. }
  70. }
  71. }
  72. // Sorts [begin, end) using insertion sort with the given comparison function. Assumes
  73. // *(begin - 1) is an element smaller than or equal to any element in [begin, end).
  74. template<class Iter, class Compare>
  75. inline void unguarded_insertion_sort(Iter begin, Iter end, Compare comp) {
  76. typedef typename std::iterator_traits<Iter>::value_type T;
  77. if (begin == end) return;
  78. for (Iter cur = begin + 1; cur != end; ++cur) {
  79. Iter sift = cur;
  80. Iter sift_1 = cur - 1;
  81. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  82. if (comp(*sift, *sift_1)) {
  83. T tmp = PDQSORT_PREFER_MOVE(*sift);
  84. do { *sift-- = PDQSORT_PREFER_MOVE(*sift_1); }
  85. while (comp(tmp, *--sift_1));
  86. *sift = PDQSORT_PREFER_MOVE(tmp);
  87. }
  88. }
  89. }
  90. // Attempts to use insertion sort on [begin, end). Will return false if more than
  91. // partial_insertion_sort_limit elements were moved, and abort sorting. Otherwise it will
  92. // successfully sort and return true.
  93. template<class Iter, class Compare>
  94. inline bool partial_insertion_sort(Iter begin, Iter end, Compare comp) {
  95. typedef typename std::iterator_traits<Iter>::value_type T;
  96. if (begin == end) return true;
  97. std::size_t limit = 0;
  98. for (Iter cur = begin + 1; cur != end; ++cur) {
  99. Iter sift = cur;
  100. Iter sift_1 = cur - 1;
  101. // Compare first so we can avoid 2 moves for an element already positioned correctly.
  102. if (comp(*sift, *sift_1)) {
  103. T tmp = PDQSORT_PREFER_MOVE(*sift);
  104. do { *sift-- = PDQSORT_PREFER_MOVE(*sift_1); }
  105. while (sift != begin && comp(tmp, *--sift_1));
  106. *sift = PDQSORT_PREFER_MOVE(tmp);
  107. limit += cur - sift;
  108. }
  109. if (limit > partial_insertion_sort_limit) return false;
  110. }
  111. return true;
  112. }
  113. template<class Iter, class Compare>
  114. inline void sort2(Iter a, Iter b, Compare comp) {
  115. if (comp(*b, *a)) std::iter_swap(a, b);
  116. }
  117. // Sorts the elements *a, *b and *c using comparison function comp.
  118. template<class Iter, class Compare>
  119. inline void sort3(Iter a, Iter b, Iter c, Compare comp) {
  120. sort2(a, b, comp);
  121. sort2(b, c, comp);
  122. sort2(a, b, comp);
  123. }
  124. template<class T>
  125. inline T* align_cacheline(T* p) {
  126. #if defined(UINTPTR_MAX) && __cplusplus >= 201103L
  127. std::uintptr_t ip = reinterpret_cast<std::uintptr_t>(p);
  128. #else
  129. std::size_t ip = reinterpret_cast<std::size_t>(p);
  130. #endif
  131. ip = (ip + cacheline_size - 1) & -cacheline_size;
  132. return reinterpret_cast<T*>(ip);
  133. }
  134. template<class Iter>
  135. inline void swap_offsets(Iter first, Iter last,
  136. unsigned char* offsets_l, unsigned char* offsets_r,
  137. size_t num, bool use_swaps) {
  138. typedef typename std::iterator_traits<Iter>::value_type T;
  139. if (use_swaps) {
  140. // This case is needed for the descending distribution, where we need
  141. // to have proper swapping for pdqsort to remain O(n).
  142. for (size_t i = 0; i < num; ++i) {
  143. std::iter_swap(first + offsets_l[i], last - offsets_r[i]);
  144. }
  145. } else if (num > 0) {
  146. Iter l = first + offsets_l[0]; Iter r = last - offsets_r[0];
  147. T tmp(PDQSORT_PREFER_MOVE(*l)); *l = PDQSORT_PREFER_MOVE(*r);
  148. for (size_t i = 1; i < num; ++i) {
  149. l = first + offsets_l[i]; *r = PDQSORT_PREFER_MOVE(*l);
  150. r = last - offsets_r[i]; *l = PDQSORT_PREFER_MOVE(*r);
  151. }
  152. *r = PDQSORT_PREFER_MOVE(tmp);
  153. }
  154. }
  155. // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
  156. // to the pivot are put in the right-hand partition. Returns the position of the pivot after
  157. // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
  158. // pivot is a median of at least 3 elements and that [begin, end) is at least
  159. // insertion_sort_threshold long. Uses branchless partitioning.
  160. template<class Iter, class Compare>
  161. inline std::pair<Iter, bool> partition_right_branchless(Iter begin, Iter end, Compare comp) {
  162. typedef typename std::iterator_traits<Iter>::value_type T;
  163. // Move pivot into local for speed.
  164. T pivot(PDQSORT_PREFER_MOVE(*begin));
  165. Iter first = begin;
  166. Iter last = end;
  167. // Find the first element greater than or equal than the pivot (the median of 3 guarantees
  168. // this exists).
  169. while (comp(*++first, pivot));
  170. // Find the first element strictly smaller than the pivot. We have to guard this search if
  171. // there was no element before *first.
  172. if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
  173. else while ( !comp(*--last, pivot));
  174. // If the first pair of elements that should be swapped to partition are the same element,
  175. // the passed in sequence already was correctly partitioned.
  176. bool already_partitioned = first >= last;
  177. if (!already_partitioned) {
  178. std::iter_swap(first, last);
  179. ++first;
  180. // The following branchless partitioning is derived from "BlockQuicksort: How Branch
  181. // Mispredictions don’t affect Quicksort" by Stefan Edelkamp and Armin Weiss, but
  182. // heavily micro-optimized.
  183. unsigned char offsets_l_storage[block_size + cacheline_size];
  184. unsigned char offsets_r_storage[block_size + cacheline_size];
  185. unsigned char* offsets_l = align_cacheline(offsets_l_storage);
  186. unsigned char* offsets_r = align_cacheline(offsets_r_storage);
  187. Iter offsets_l_base = first;
  188. Iter offsets_r_base = last;
  189. size_t num_l, num_r, start_l, start_r;
  190. num_l = num_r = start_l = start_r = 0;
  191. while (first < last) {
  192. // Fill up offset blocks with elements that are on the wrong side.
  193. // First we determine how much elements are considered for each offset block.
  194. size_t num_unknown = last - first;
  195. size_t left_split = num_l == 0 ? (num_r == 0 ? num_unknown / 2 : num_unknown) : 0;
  196. size_t right_split = num_r == 0 ? (num_unknown - left_split) : 0;
  197. // Fill the offset blocks.
  198. if (left_split >= block_size) {
  199. for (size_t i = 0; i < block_size;) {
  200. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  201. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  202. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  203. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  204. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  205. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  206. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  207. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  208. }
  209. } else {
  210. for (size_t i = 0; i < left_split;) {
  211. offsets_l[num_l] = i++; num_l += !comp(*first, pivot); ++first;
  212. }
  213. }
  214. if (right_split >= block_size) {
  215. for (size_t i = 0; i < block_size;) {
  216. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  217. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  218. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  219. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  220. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  221. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  222. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  223. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  224. }
  225. } else {
  226. for (size_t i = 0; i < right_split;) {
  227. offsets_r[num_r] = ++i; num_r += comp(*--last, pivot);
  228. }
  229. }
  230. // Swap elements and update block sizes and first/last boundaries.
  231. size_t num = std::min(num_l, num_r);
  232. swap_offsets(offsets_l_base, offsets_r_base,
  233. offsets_l + start_l, offsets_r + start_r,
  234. num, num_l == num_r);
  235. num_l -= num; num_r -= num;
  236. start_l += num; start_r += num;
  237. if (num_l == 0) {
  238. start_l = 0;
  239. offsets_l_base = first;
  240. }
  241. if (num_r == 0) {
  242. start_r = 0;
  243. offsets_r_base = last;
  244. }
  245. }
  246. // We have now fully identified [first, last)'s proper position. Swap the last elements.
  247. if (num_l) {
  248. offsets_l += start_l;
  249. while (num_l--) std::iter_swap(offsets_l_base + offsets_l[num_l], --last);
  250. first = last;
  251. }
  252. if (num_r) {
  253. offsets_r += start_r;
  254. while (num_r--) std::iter_swap(offsets_r_base - offsets_r[num_r], first), ++first;
  255. last = first;
  256. }
  257. }
  258. // Put the pivot in the right place.
  259. Iter pivot_pos = first - 1;
  260. *begin = PDQSORT_PREFER_MOVE(*pivot_pos);
  261. *pivot_pos = PDQSORT_PREFER_MOVE(pivot);
  262. return std::make_pair(pivot_pos, already_partitioned);
  263. }
  264. // Partitions [begin, end) around pivot *begin using comparison function comp. Elements equal
  265. // to the pivot are put in the right-hand partition. Returns the position of the pivot after
  266. // partitioning and whether the passed sequence already was correctly partitioned. Assumes the
  267. // pivot is a median of at least 3 elements and that [begin, end) is at least
  268. // insertion_sort_threshold long.
  269. template<class Iter, class Compare>
  270. inline std::pair<Iter, bool> partition_right(Iter begin, Iter end, Compare comp) {
  271. typedef typename std::iterator_traits<Iter>::value_type T;
  272. // Move pivot into local for speed.
  273. T pivot(PDQSORT_PREFER_MOVE(*begin));
  274. Iter first = begin;
  275. Iter last = end;
  276. // Find the first element greater than or equal than the pivot (the median of 3 guarantees
  277. // this exists).
  278. while (comp(*++first, pivot));
  279. // Find the first element strictly smaller than the pivot. We have to guard this search if
  280. // there was no element before *first.
  281. if (first - 1 == begin) while (first < last && !comp(*--last, pivot));
  282. else while ( !comp(*--last, pivot));
  283. // If the first pair of elements that should be swapped to partition are the same element,
  284. // the passed in sequence already was correctly partitioned.
  285. bool already_partitioned = first >= last;
  286. // Keep swapping pairs of elements that are on the wrong side of the pivot. Previously
  287. // swapped pairs guard the searches, which is why the first iteration is special-cased
  288. // above.
  289. while (first < last) {
  290. std::iter_swap(first, last);
  291. while (comp(*++first, pivot));
  292. while (!comp(*--last, pivot));
  293. }
  294. // Put the pivot in the right place.
  295. Iter pivot_pos = first - 1;
  296. *begin = PDQSORT_PREFER_MOVE(*pivot_pos);
  297. *pivot_pos = PDQSORT_PREFER_MOVE(pivot);
  298. return std::make_pair(pivot_pos, already_partitioned);
  299. }
  300. // Similar function to the one above, except elements equal to the pivot are put to the left of
  301. // the pivot and it doesn't check or return if the passed sequence already was partitioned.
  302. // Since this is rarely used (the many equal case), and in that case pdqsort already has O(n)
  303. // performance, no block quicksort is applied here for simplicity.
  304. template<class Iter, class Compare>
  305. inline Iter partition_left(Iter begin, Iter end, Compare comp) {
  306. typedef typename std::iterator_traits<Iter>::value_type T;
  307. T pivot(PDQSORT_PREFER_MOVE(*begin));
  308. Iter first = begin;
  309. Iter last = end;
  310. while (comp(pivot, *--last));
  311. if (last + 1 == end) while (first < last && !comp(pivot, *++first));
  312. else while ( !comp(pivot, *++first));
  313. while (first < last) {
  314. std::iter_swap(first, last);
  315. while (comp(pivot, *--last));
  316. while (!comp(pivot, *++first));
  317. }
  318. Iter pivot_pos = last;
  319. *begin = PDQSORT_PREFER_MOVE(*pivot_pos);
  320. *pivot_pos = PDQSORT_PREFER_MOVE(pivot);
  321. return pivot_pos;
  322. }
  323. template<class Iter, class Compare, bool Branchless>
  324. inline void pdqsort_loop(Iter begin, Iter end, Compare comp, int bad_allowed, bool leftmost = true) {
  325. typedef typename std::iterator_traits<Iter>::difference_type diff_t;
  326. // Use a while loop for tail recursion elimination.
  327. while (true) {
  328. diff_t size = end - begin;
  329. // Insertion sort is faster for small arrays.
  330. if (size < insertion_sort_threshold) {
  331. if (leftmost) insertion_sort(begin, end, comp);
  332. else unguarded_insertion_sort(begin, end, comp);
  333. return;
  334. }
  335. // Choose pivot as median of 3 or pseudomedian of 9.
  336. diff_t s2 = size / 2;
  337. if (size > ninther_threshold) {
  338. sort3(begin, begin + s2, end - 1, comp);
  339. sort3(begin + 1, begin + (s2 - 1), end - 2, comp);
  340. sort3(begin + 2, begin + (s2 + 1), end - 3, comp);
  341. sort3(begin + (s2 - 1), begin + s2, begin + (s2 + 1), comp);
  342. std::iter_swap(begin, begin + s2);
  343. } else sort3(begin + s2, begin, end - 1, comp);
  344. // If *(begin - 1) is the end of the right partition of a previous partition operation
  345. // there is no element in [begin, end) that is smaller than *(begin - 1). Then if our
  346. // pivot compares equal to *(begin - 1) we change strategy, putting equal elements in
  347. // the left partition, greater elements in the right partition. We do not have to
  348. // recurse on the left partition, since it's sorted (all equal).
  349. if (!leftmost && !comp(*(begin - 1), *begin)) {
  350. begin = partition_left(begin, end, comp) + 1;
  351. continue;
  352. }
  353. // Partition and get results.
  354. std::pair<Iter, bool> part_result =
  355. Branchless ? partition_right_branchless(begin, end, comp)
  356. : partition_right(begin, end, comp);
  357. Iter pivot_pos = part_result.first;
  358. bool already_partitioned = part_result.second;
  359. // Check for a highly unbalanced partition.
  360. diff_t l_size = pivot_pos - begin;
  361. diff_t r_size = end - (pivot_pos + 1);
  362. bool highly_unbalanced = l_size < size / 8 || r_size < size / 8;
  363. // If we got a highly unbalanced partition we shuffle elements to break many patterns.
  364. if (highly_unbalanced) {
  365. // If we had too many bad partitions, switch to heapsort to guarantee O(n log n).
  366. if (--bad_allowed == 0) {
  367. std::make_heap(begin, end, comp);
  368. std::sort_heap(begin, end, comp);
  369. return;
  370. }
  371. if (l_size >= insertion_sort_threshold) {
  372. std::iter_swap(begin, begin + l_size / 4);
  373. std::iter_swap(pivot_pos - 1, pivot_pos - l_size / 4);
  374. if (l_size > ninther_threshold) {
  375. std::iter_swap(begin + 1, begin + (l_size / 4 + 1));
  376. std::iter_swap(begin + 2, begin + (l_size / 4 + 2));
  377. std::iter_swap(pivot_pos - 2, pivot_pos - (l_size / 4 + 1));
  378. std::iter_swap(pivot_pos - 3, pivot_pos - (l_size / 4 + 2));
  379. }
  380. }
  381. if (r_size >= insertion_sort_threshold) {
  382. std::iter_swap(pivot_pos + 1, pivot_pos + (1 + r_size / 4));
  383. std::iter_swap(end - 1, end - r_size / 4);
  384. if (r_size > ninther_threshold) {
  385. std::iter_swap(pivot_pos + 2, pivot_pos + (2 + r_size / 4));
  386. std::iter_swap(pivot_pos + 3, pivot_pos + (3 + r_size / 4));
  387. std::iter_swap(end - 2, end - (1 + r_size / 4));
  388. std::iter_swap(end - 3, end - (2 + r_size / 4));
  389. }
  390. }
  391. } else {
  392. // If we were decently balanced and we tried to sort an already partitioned
  393. // sequence try to use insertion sort.
  394. if (already_partitioned && partial_insertion_sort(begin, pivot_pos, comp)
  395. && partial_insertion_sort(pivot_pos + 1, end, comp)) return;
  396. }
  397. // Sort the left partition first using recursion and do tail recursion elimination for
  398. // the right-hand partition.
  399. pdqsort_loop<Iter, Compare, Branchless>(begin, pivot_pos, comp, bad_allowed, leftmost);
  400. begin = pivot_pos + 1;
  401. leftmost = false;
  402. }
  403. }
  404. }
  405. template<class Iter, class Compare>
  406. inline void pdqsort(Iter begin, Iter end, Compare comp) {
  407. if (begin == end) return;
  408. #if __cplusplus >= 201103L
  409. pdqsort_detail::pdqsort_loop<Iter, Compare,
  410. pdqsort_detail::is_default_compare<typename std::decay<Compare>::type>::value &&
  411. std::is_arithmetic<typename std::iterator_traits<Iter>::value_type>::value>(
  412. begin, end, comp, pdqsort_detail::log2(end - begin));
  413. #else
  414. pdqsort_detail::pdqsort_loop<Iter, Compare, false>(
  415. begin, end, comp, pdqsort_detail::log2(end - begin));
  416. #endif
  417. }
  418. template<class Iter>
  419. inline void pdqsort(Iter begin, Iter end) {
  420. typedef typename std::iterator_traits<Iter>::value_type T;
  421. pdqsort(begin, end, std::less<T>());
  422. }
  423. template<class Iter, class Compare>
  424. inline void pdqsort_branchless(Iter begin, Iter end, Compare comp) {
  425. if (begin == end) return;
  426. pdqsort_detail::pdqsort_loop<Iter, Compare, true>(
  427. begin, end, comp, pdqsort_detail::log2(end - begin));
  428. }
  429. template<class Iter>
  430. inline void pdqsort_branchless(Iter begin, Iter end) {
  431. typedef typename std::iterator_traits<Iter>::value_type T;
  432. pdqsort_branchless(begin, end, std::less<T>());
  433. }
  434. #undef PDQSORT_PREFER_MOVE
  435. #endif