sift_down.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_SIFT_DOWN_H
  9. #define _LIBCPP___ALGORITHM_SIFT_DOWN_H
  10. #include <__config>
  11. #include <__iterator/iterator_traits.h>
  12. #include <__utility/move.h>
  13. #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
  14. # pragma GCC system_header
  15. #endif
  16. _LIBCPP_BEGIN_NAMESPACE_STD
  17. template <class _Compare, class _RandomAccessIterator>
  18. _LIBCPP_CONSTEXPR_AFTER_CXX11 void
  19. __sift_down(_RandomAccessIterator __first, _Compare __comp,
  20. typename iterator_traits<_RandomAccessIterator>::difference_type __len,
  21. _RandomAccessIterator __start)
  22. {
  23. typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
  24. typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
  25. // left-child of __start is at 2 * __start + 1
  26. // right-child of __start is at 2 * __start + 2
  27. difference_type __child = __start - __first;
  28. if (__len < 2 || (__len - 2) / 2 < __child)
  29. return;
  30. __child = 2 * __child + 1;
  31. _RandomAccessIterator __child_i = __first + __child;
  32. if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + difference_type(1)))) {
  33. // right-child exists and is greater than left-child
  34. ++__child_i;
  35. ++__child;
  36. }
  37. // check if we are in heap-order
  38. if (__comp(*__child_i, *__start))
  39. // we are, __start is larger than its largest child
  40. return;
  41. value_type __top(_VSTD::move(*__start));
  42. do
  43. {
  44. // we are not in heap-order, swap the parent with its largest child
  45. *__start = _VSTD::move(*__child_i);
  46. __start = __child_i;
  47. if ((__len - 2) / 2 < __child)
  48. break;
  49. // recompute the child based off of the updated parent
  50. __child = 2 * __child + 1;
  51. __child_i = __first + __child;
  52. if ((__child + 1) < __len && __comp(*__child_i, *(__child_i + difference_type(1)))) {
  53. // right-child exists and is greater than left-child
  54. ++__child_i;
  55. ++__child;
  56. }
  57. // check if we are in heap-order
  58. } while (!__comp(*__child_i, __top));
  59. *__start = _VSTD::move(__top);
  60. }
  61. _LIBCPP_END_NAMESPACE_STD
  62. #endif // _LIBCPP___ALGORITHM_SIFT_DOWN_H