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