Petrovi4

LowerBound

Aug 19th, 2022 (edited)
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <algorithm>
  2. #include <execution>
  3. #include <future>
  4.  
  5. using namespace std;
  6.  
  7. template <typename RandomAccessIterator, typename Value>
  8. RandomAccessIterator LowerBound(const execution::sequenced_policy&, RandomAccessIterator range_begin, RandomAccessIterator range_end, const Value& value) {
  9.     return lower_bound(range_begin, range_end, value);
  10. }
  11.  
  12. template <typename RandomAccessIterator, typename Value>
  13. RandomAccessIterator LowerBound(RandomAccessIterator range_begin, RandomAccessIterator range_end, const Value& value) {
  14.     return LowerBound(execution::seq, range_begin, range_end, value);
  15. }
  16.  
  17. template <typename RandomAccessIterator, typename Value>
  18. RandomAccessIterator LowerBound(const execution::parallel_policy&, RandomAccessIterator range_begin, RandomAccessIterator range_end, const Value& value) {
  19.     auto left_bound = range_begin;
  20.     auto right_bound = range_end;
  21.     while (left_bound + 1 < right_bound) {
  22.         const int distance = right_bound - left_bound;
  23.         const int part_length = max(1, distance / 3);
  24.         const auto middle_left = left_bound + part_length;
  25.         const auto middle_right = right_bound - part_length;
  26.  
  27.         auto left_less_future = async([middle_left, &value] { return *middle_left < value; });
  28.  
  29.         if (*middle_right < value) {
  30.             left_bound = middle_right;
  31.         } else if (left_less_future.get()) {
  32.             left_bound = middle_left;
  33.             right_bound = middle_right;
  34.         } else {
  35.             right_bound = middle_left;
  36.         }
  37.     }
  38.     if (left_bound == range_begin && !(*left_bound < value)) {
  39.         return left_bound;
  40.     } else {
  41.         return right_bound;
  42.     }
  43. }
Add Comment
Please, Sign In to add comment