-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search.hpp
100 lines (76 loc) · 2.17 KB
/
binary_search.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
/// Problem source:
/// https://en.wikipedia.org/wiki/Binary_search_algorithm
#ifndef FORFUN_SEARCH_BINARY_SEARCH_HPP_
#define FORFUN_SEARCH_BINARY_SEARCH_HPP_
#include <iterator>
namespace forfun::search::binary_search {
namespace iterative {
template <std::random_access_iterator Itr, typename Target>
[[nodiscard]] constexpr auto
find(Itr lhs, Itr const last, Target const target) noexcept -> Itr
{
using DiffType = std::iter_difference_t<Itr>;
for (Itr rhs{last}; lhs != rhs;)
{
auto const distance{std::distance(lhs, rhs)};
Itr mid{std::next(lhs, distance / DiffType{2})};
if (target < *mid)
{
rhs = mid;
}
else if (target > *mid)
{
std::advance(mid, distance % DiffType{2});
lhs = mid;
}
else
{
return mid;
}
}
return last;
}
} // namespace iterative
namespace recursive {
namespace detail {
template <std::random_access_iterator Itr, typename Target>
[[nodiscard]] constexpr auto
do_find(Itr const first, Itr const last, Target const target) noexcept -> Itr
{
using DiffType = std::iter_difference_t<Itr>;
auto const distance{std::distance(first, last)};
if (distance < DiffType{1})
{
return last;
}
Itr mid{std::next(first, distance / DiffType{2})};
if (target < *mid)
{
return do_find(first, mid, target);
}
if (target > *mid)
{
std::advance(mid, distance % DiffType{2});
return do_find(mid, last, target);
}
return mid;
}
} // namespace detail
template <std::random_access_iterator Itr, typename Target>
[[nodiscard]] constexpr auto
find(Itr const first, Itr const last, Target const target) noexcept -> Itr
{
if (Itr const itr{detail::do_find(first, last, target)};
(itr != last) && (*itr == target))
{
return itr;
}
return last;
}
} // namespace recursive
} // namespace forfun::search::binary_search
#endif // FORFUN_SEARCH_BINARY_SEARCH_HPP_