xref: /llvm-project/libcxx/include/__algorithm/partial_sort.h (revision 2aea8af25136b2d336249d099e254639168b33c7)
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 
9 #ifndef _LIBCPP___ALGORITHM_PARTIAL_SORT_H
10 #define _LIBCPP___ALGORITHM_PARTIAL_SORT_H
11 
12 #include <__algorithm/comp.h>
13 #include <__algorithm/comp_ref_type.h>
14 #include <__algorithm/make_heap.h>
15 #include <__algorithm/sift_down.h>
16 #include <__algorithm/sort_heap.h>
17 #include <__config>
18 #include <__debug>
19 #include <__debug_utils/randomize_range.h>
20 #include <__iterator/iterator_traits.h>
21 #include <__utility/swap.h>
22 
23 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
24 #  pragma GCC system_header
25 #endif
26 
27 _LIBCPP_BEGIN_NAMESPACE_STD
28 
29 template <class _Compare, class _RandomAccessIterator>
30 _LIBCPP_CONSTEXPR_AFTER_CXX17 void
31 __partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
32                _Compare __comp)
33 {
34     if (__first == __middle)
35         return;
36     _VSTD::__make_heap<_Compare>(__first, __middle, __comp);
37     typename iterator_traits<_RandomAccessIterator>::difference_type __len = __middle - __first;
38     for (_RandomAccessIterator __i = __middle; __i != __last; ++__i)
39     {
40         if (__comp(*__i, *__first))
41         {
42             swap(*__i, *__first);
43             _VSTD::__sift_down<_Compare>(__first, __comp, __len, __first);
44         }
45     }
46     _VSTD::__sort_heap<_Compare>(__first, __middle, __comp);
47 }
48 
49 template <class _RandomAccessIterator, class _Compare>
50 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
51 void
52 partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last,
53              _Compare __comp)
54 {
55   std::__debug_randomize_range(__first, __last);
56   typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
57   _VSTD::__partial_sort<_Comp_ref>(__first, __middle, __last, __comp);
58   std::__debug_randomize_range(__middle, __last);
59 }
60 
61 template <class _RandomAccessIterator>
62 inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX17
63 void
64 partial_sort(_RandomAccessIterator __first, _RandomAccessIterator __middle, _RandomAccessIterator __last)
65 {
66     _VSTD::partial_sort(__first, __middle, __last,
67                         __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
68 }
69 
70 _LIBCPP_END_NAMESPACE_STD
71 
72 #endif // _LIBCPP___ALGORITHM_PARTIAL_SORT_H
73