[libcxx-commits] [PATCH] D141614: [libc++] nth_element change to partial sort when range is really small
Zhikai Zeng via Phabricator via libcxx-commits
libcxx-commits at lists.llvm.org
Thu Jan 12 07:52:56 PST 2023
Backl1ght created this revision.
Backl1ght added reviewers: philnik, ldionne.
Backl1ght added a project: libc++.
Herald added a project: All.
Backl1ght requested review of this revision.
Herald added a subscriber: libcxx-commits.
Herald added a reviewer: libc++.
for really small range, we don't need to sort the whole range, we only need to do partial sort, this can reduce some calculations.
Repository:
rG LLVM Github Monorepo
https://reviews.llvm.org/D141614
Files:
libcxx/include/__algorithm/nth_element.h
Index: libcxx/include/__algorithm/nth_element.h
===================================================================
--- libcxx/include/__algorithm/nth_element.h
+++ libcxx/include/__algorithm/nth_element.h
@@ -12,6 +12,7 @@
#include <__algorithm/comp.h>
#include <__algorithm/comp_ref_type.h>
#include <__algorithm/iterator_operations.h>
+#include <__algorithm/min_element.h>
#include <__algorithm/sort.h>
#include <__config>
#include <__debug>
@@ -25,6 +26,20 @@
_LIBCPP_BEGIN_NAMESPACE_STD
+// Assumes size > 0
+template <class _AlgPolicy, class _Compare, class _BidirectionalIterator>
+_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 void __selection_partial_sort(
+ _BidirectionalIterator __first, _BidirectionalIterator __nth, _BidirectionalIterator __last, _Compare __comp) {
+ _BidirectionalIterator __lm1 = __nth;
+ if (++__lm1 == __last)
+ --__lm1;
+ for (; __first != __lm1; ++__first) {
+ _BidirectionalIterator __i = std::__min_element<_Compare>(__first, __last, __comp);
+ if (__i != __first)
+ _IterOps<_AlgPolicy>::iter_swap(__first, __i);
+ }
+}
+
template<class _Compare, class _RandomAccessIterator>
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX14 bool
__nth_element_find_guard(_RandomAccessIterator& __i, _RandomAccessIterator& __j,
@@ -73,7 +88,7 @@
}
if (__len <= __limit)
{
- std::__selection_sort<_AlgPolicy, _Compare>(__first, __last, __comp);
+ std::__selection_partial_sort<_AlgPolicy, _Compare>(__first, __nth, __last, __comp);
return;
}
// __len > __limit >= 3
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D141614.488654.patch
Type: text/x-patch
Size: 1612 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libcxx-commits/attachments/20230112/8cae6204/attachment.bin>
More information about the libcxx-commits
mailing list