nth_element.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. //===----------------------------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef _LIBCPP___ALGORITHM_NTH_ELEMENT_H
  9. #define _LIBCPP___ALGORITHM_NTH_ELEMENT_H
  10. #include <__algorithm/comp.h>
  11. #include <__algorithm/comp_ref_type.h>
  12. #include <__algorithm/iterator_operations.h>
  13. #include <__algorithm/sort.h>
  14. #include <__assert>
  15. #include <__config>
  16. #include <__debug_utils/randomize_range.h>
  17. #include <__iterator/iterator_traits.h>
  18. #include <__utility/move.h>
  19. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  20. # pragma GCC system_header
  21. #endif
  22. _LIBCPP_PUSH_MACROS
  23. #include <__undef_macros>
  24. _LIBCPP_BEGIN_NAMESPACE_STD
  25. template <class _Compare, class _RandomAccessIterator>
  26. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 bool __nth_element_find_guard(
  27. _RandomAccessIterator& __i, _RandomAccessIterator& __j, _RandomAccessIterator __m, _Compare __comp) {
  28. // manually guard downward moving __j against __i
  29. while (true) {
  30. if (__i == --__j) {
  31. return false;
  32. }
  33. if (__comp(*__j, *__m)) {
  34. return true; // found guard for downward moving __j, now use unguarded partition
  35. }
  36. }
  37. }
  38. template <class _AlgPolicy, class _Compare, class _RandomAccessIterator>
  39. _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void
  40. // NOLINTNEXTLINE(readability-function-cognitive-complexity)
  41. __nth_element(
  42. _RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp) {
  43. using _Ops = _IterOps<_AlgPolicy>;
  44. // _Compare is known to be a reference type
  45. typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
  46. const difference_type __limit = 7;
  47. while (true) {
  48. if (__nth == __last)
  49. return;
  50. difference_type __len = __last - __first;
  51. switch (__len) {
  52. case 0:
  53. case 1:
  54. return;
  55. case 2:
  56. if (__comp(*--__last, *__first))
  57. _Ops::iter_swap(__first, __last);
  58. return;
  59. case 3: {
  60. _RandomAccessIterator __m = __first;
  61. std::__sort3<_AlgPolicy, _Compare>(__first, ++__m, --__last, __comp);
  62. return;
  63. }
  64. }
  65. if (__len <= __limit) {
  66. std::__selection_sort<_AlgPolicy, _Compare>(__first, __last, __comp);
  67. return;
  68. }
  69. // __len > __limit >= 3
  70. _RandomAccessIterator __m = __first + __len / 2;
  71. _RandomAccessIterator __lm1 = __last;
  72. unsigned __n_swaps = std::__sort3<_AlgPolicy, _Compare>(__first, __m, --__lm1, __comp);
  73. // *__m is median
  74. // partition [__first, __m) < *__m and *__m <= [__m, __last)
  75. // (this inhibits tossing elements equivalent to __m around unnecessarily)
  76. _RandomAccessIterator __i = __first;
  77. _RandomAccessIterator __j = __lm1;
  78. // j points beyond range to be tested, *__lm1 is known to be <= *__m
  79. // The search going up is known to be guarded but the search coming down isn't.
  80. // Prime the downward search with a guard.
  81. if (!__comp(*__i, *__m)) // if *__first == *__m
  82. {
  83. // *__first == *__m, *__first doesn't go in first part
  84. if (std::__nth_element_find_guard<_Compare>(__i, __j, __m, __comp)) {
  85. _Ops::iter_swap(__i, __j);
  86. ++__n_swaps;
  87. } else {
  88. // *__first == *__m, *__m <= all other elements
  89. // Partition instead into [__first, __i) == *__first and *__first < [__i, __last)
  90. ++__i; // __first + 1
  91. __j = __last;
  92. if (!__comp(*__first, *--__j)) { // we need a guard if *__first == *(__last-1)
  93. while (true) {
  94. if (__i == __j) {
  95. return; // [__first, __last) all equivalent elements
  96. } else if (__comp(*__first, *__i)) {
  97. _Ops::iter_swap(__i, __j);
  98. ++__n_swaps;
  99. ++__i;
  100. break;
  101. }
  102. ++__i;
  103. }
  104. }
  105. // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
  106. if (__i == __j) {
  107. return;
  108. }
  109. while (true) {
  110. while (!__comp(*__first, *__i)) {
  111. ++__i;
  112. _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
  113. __i != __last,
  114. "Would read out of bounds, does your comparator satisfy the strict-weak ordering requirement?");
  115. }
  116. do {
  117. _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
  118. __j != __first,
  119. "Would read out of bounds, does your comparator satisfy the strict-weak ordering requirement?");
  120. --__j;
  121. } while (__comp(*__first, *__j));
  122. if (__i >= __j)
  123. break;
  124. _Ops::iter_swap(__i, __j);
  125. ++__n_swaps;
  126. ++__i;
  127. }
  128. // [__first, __i) == *__first and *__first < [__i, __last)
  129. // The first part is sorted,
  130. if (__nth < __i) {
  131. return;
  132. }
  133. // __nth_element the second part
  134. // std::__nth_element<_Compare>(__i, __nth, __last, __comp);
  135. __first = __i;
  136. continue;
  137. }
  138. }
  139. ++__i;
  140. // j points beyond range to be tested, *__lm1 is known to be <= *__m
  141. // if not yet partitioned...
  142. if (__i < __j) {
  143. // known that *(__i - 1) < *__m
  144. while (true) {
  145. // __m still guards upward moving __i
  146. while (__comp(*__i, *__m)) {
  147. ++__i;
  148. _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
  149. __i != __last,
  150. "Would read out of bounds, does your comparator satisfy the strict-weak ordering requirement?");
  151. }
  152. // It is now known that a guard exists for downward moving __j
  153. do {
  154. _LIBCPP_ASSERT_VALID_ELEMENT_ACCESS(
  155. __j != __first,
  156. "Would read out of bounds, does your comparator satisfy the strict-weak ordering requirement?");
  157. --__j;
  158. } while (!__comp(*__j, *__m));
  159. if (__i >= __j)
  160. break;
  161. _Ops::iter_swap(__i, __j);
  162. ++__n_swaps;
  163. // It is known that __m != __j
  164. // If __m just moved, follow it
  165. if (__m == __i)
  166. __m = __j;
  167. ++__i;
  168. }
  169. }
  170. // [__first, __i) < *__m and *__m <= [__i, __last)
  171. if (__i != __m && __comp(*__m, *__i)) {
  172. _Ops::iter_swap(__i, __m);
  173. ++__n_swaps;
  174. }
  175. // [__first, __i) < *__i and *__i <= [__i+1, __last)
  176. if (__nth == __i)
  177. return;
  178. if (__n_swaps == 0) {
  179. // We were given a perfectly partitioned sequence. Coincidence?
  180. if (__nth < __i) {
  181. // Check for [__first, __i) already sorted
  182. __j = __m = __first;
  183. while (true) {
  184. if (++__j == __i) {
  185. // [__first, __i) sorted
  186. return;
  187. }
  188. if (__comp(*__j, *__m)) {
  189. // not yet sorted, so sort
  190. break;
  191. }
  192. __m = __j;
  193. }
  194. } else {
  195. // Check for [__i, __last) already sorted
  196. __j = __m = __i;
  197. while (true) {
  198. if (++__j == __last) {
  199. // [__i, __last) sorted
  200. return;
  201. }
  202. if (__comp(*__j, *__m)) {
  203. // not yet sorted, so sort
  204. break;
  205. }
  206. __m = __j;
  207. }
  208. }
  209. }
  210. // __nth_element on range containing __nth
  211. if (__nth < __i) {
  212. // std::__nth_element<_Compare>(__first, __nth, __i, __comp);
  213. __last = __i;
  214. } else {
  215. // std::__nth_element<_Compare>(__i+1, __nth, __last, __comp);
  216. __first = ++__i;
  217. }
  218. }
  219. }
  220. template <class _AlgPolicy, class _RandomAccessIterator, class _Compare>
  221. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void __nth_element_impl(
  222. _RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare& __comp) {
  223. if (__nth == __last)
  224. return;
  225. std::__debug_randomize_range<_AlgPolicy>(__first, __last);
  226. std::__nth_element<_AlgPolicy, __comp_ref_type<_Compare> >(__first, __nth, __last, __comp);
  227. std::__debug_randomize_range<_AlgPolicy>(__first, __nth);
  228. if (__nth != __last) {
  229. std::__debug_randomize_range<_AlgPolicy>(++__nth, __last);
  230. }
  231. }
  232. template <class _RandomAccessIterator, class _Compare>
  233. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
  234. nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last, _Compare __comp) {
  235. std::__nth_element_impl<_ClassicAlgPolicy>(std::move(__first), std::move(__nth), std::move(__last), __comp);
  236. }
  237. template <class _RandomAccessIterator>
  238. inline _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX20 void
  239. nth_element(_RandomAccessIterator __first, _RandomAccessIterator __nth, _RandomAccessIterator __last) {
  240. std::nth_element(std::move(__first), std::move(__nth), std::move(__last), __less<>());
  241. }
  242. _LIBCPP_END_NAMESPACE_STD
  243. _LIBCPP_POP_MACROS
  244. #endif // _LIBCPP___ALGORITHM_NTH_ELEMENT_H