1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_BinarySearch_h
8 #define mozilla_BinarySearch_h
10 #include "mozilla/Assertions.h"
11 #include "mozilla/CompactPair.h"
18 * The BinarySearch() algorithm searches the given container |aContainer| over
19 * the sorted index range [aBegin, aEnd) for an index |i| where
20 * |aContainer[i] == aTarget|.
21 * If such an index |i| is found, BinarySearch returns |true| and the index is
22 * returned via the outparam |aMatchOrInsertionPoint|. If no index is found,
23 * BinarySearch returns |false| and the outparam returns the first index in
24 * [aBegin, aEnd] where |aTarget| can be inserted to maintain sorted order.
28 * Vector<int> sortedInts = ...
31 * if (BinarySearch(sortedInts, 0, sortedInts.length(), 13, &match)) {
32 * printf("found 13 at %lu\n", match);
35 * The BinarySearchIf() version behaves similarly, but takes |aComparator|, a
36 * functor to compare the values with, instead of a value to find.
37 * That functor should take one argument - the value to compare - and return an
38 * |int| with the comparison result:
40 * * 0, if the argument is equal to,
41 * * less than 0, if the argument is greater than,
42 * * greater than 0, if the argument is less than
49 * int operator()(int aVal) const {
50 * if (mTarget < aVal) { return -1; }
51 * if (mTarget > aVal) { return 1; }
54 * explicit Comparator(int aTarget) : mTarget(aTarget) {}
58 * Vector<int> sortedInts = ...
61 * if (BinarySearchIf(sortedInts, 0, sortedInts.length(), Comparator(13),
62 * &match)) { printf("found 13 at %lu\n", match);
67 template <typename Container
, typename Comparator
>
68 bool BinarySearchIf(const Container
& aContainer
, size_t aBegin
, size_t aEnd
,
69 const Comparator
& aCompare
,
70 size_t* aMatchOrInsertionPoint
) {
71 MOZ_ASSERT(aBegin
<= aEnd
);
76 size_t middle
= low
+ (high
- low
) / 2;
78 // Allow any intermediate type so long as it provides a suitable ordering
80 const int result
= aCompare(aContainer
[middle
]);
83 *aMatchOrInsertionPoint
= middle
;
94 *aMatchOrInsertionPoint
= low
;
101 class BinarySearchDefaultComparator
{
103 explicit BinarySearchDefaultComparator(const T
& aTarget
) : mTarget(aTarget
) {}
106 int operator()(const U
& aVal
) const {
107 if (mTarget
== aVal
) {
111 if (mTarget
< aVal
) {
122 } // namespace detail
124 template <typename Container
, typename T
>
125 bool BinarySearch(const Container
& aContainer
, size_t aBegin
, size_t aEnd
,
126 T aTarget
, size_t* aMatchOrInsertionPoint
) {
127 return BinarySearchIf(aContainer
, aBegin
, aEnd
,
128 detail::BinarySearchDefaultComparator
<T
>(aTarget
),
129 aMatchOrInsertionPoint
);
133 * LowerBound(), UpperBound(), and EqualRange() are equivalent to
134 * std::lower_bound(), std::upper_bound(), and std::equal_range() respectively.
136 * LowerBound() returns an index pointing to the first element in the range
137 * in which each element is considered *not less than* the given value passed
138 * via |aCompare|, or the length of |aContainer| if no such element is found.
140 * UpperBound() returns an index pointing to the first element in the range
141 * in which each element is considered *greater than* the given value passed
142 * via |aCompare|, or the length of |aContainer| if no such element is found.
144 * EqualRange() returns a range [first, second) containing all elements are
145 * considered equivalent to the given value via |aCompare|. If you need
146 * either the first or last index of the range, LowerBound() or UpperBound(),
147 * which is slightly faster than EqualRange(), should suffice.
149 * Example (another example is given in TestBinarySearch.cpp):
151 * Vector<const char*> sortedStrings = ...
153 * struct Comparator {
154 * const nsACString& mStr;
155 * explicit Comparator(const nsACString& aStr) : mStr(aStr) {}
156 * int32_t operator()(const char* aVal) const {
157 * return Compare(mStr, nsDependentCString(aVal));
161 * auto bounds = EqualRange(sortedStrings, 0, sortedStrings.length(),
162 * Comparator("needle I'm looking for"_ns));
163 * printf("Found the range [%zd %zd)\n", bounds.first(), bounds.second());
166 template <typename Container
, typename Comparator
>
167 size_t LowerBound(const Container
& aContainer
, size_t aBegin
, size_t aEnd
,
168 const Comparator
& aCompare
) {
169 MOZ_ASSERT(aBegin
<= aEnd
);
173 while (high
!= low
) {
174 size_t middle
= low
+ (high
- low
) / 2;
176 // Allow any intermediate type so long as it provides a suitable ordering
178 const int result
= aCompare(aContainer
[middle
]);
180 // The range returning from LowerBound does include elements
181 // equivalent to the given value i.e. aCompare(element) == 0
192 template <typename Container
, typename Comparator
>
193 size_t UpperBound(const Container
& aContainer
, size_t aBegin
, size_t aEnd
,
194 const Comparator
& aCompare
) {
195 MOZ_ASSERT(aBegin
<= aEnd
);
199 while (high
!= low
) {
200 size_t middle
= low
+ (high
- low
) / 2;
202 // Allow any intermediate type so long as it provides a suitable ordering
204 const int result
= aCompare(aContainer
[middle
]);
206 // The range returning from UpperBound does NOT include elements
207 // equivalent to the given value i.e. aCompare(element) == 0
218 template <typename Container
, typename Comparator
>
219 CompactPair
<size_t, size_t> EqualRange(const Container
& aContainer
,
220 size_t aBegin
, size_t aEnd
,
221 const Comparator
& aCompare
) {
222 MOZ_ASSERT(aBegin
<= aEnd
);
226 while (high
!= low
) {
227 size_t middle
= low
+ (high
- low
) / 2;
229 // Allow any intermediate type so long as it provides a suitable ordering
231 const int result
= aCompare(aContainer
[middle
]);
235 } else if (result
> 0) {
238 return MakeCompactPair(
239 LowerBound(aContainer
, low
, middle
, aCompare
),
240 UpperBound(aContainer
, middle
+ 1, high
, aCompare
));
244 return MakeCompactPair(low
, high
);
247 } // namespace mozilla
249 #endif // mozilla_BinarySearch_h