Skip to content
This repository was archived by the owner on Mar 21, 2024. It is now read-only.

Commit 7749058

Browse files
r-barnesalliepiper
authored andcommitted
Fix binary search middle calculation to avoid overflows
1 parent 0203e9a commit 7749058

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

thrust/system/detail/generic/scalar/binary_search.inl

+4-5
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
5252
Size start = 0, i;
5353
while(start < n)
5454
{
55-
i = (start + n) / 2;
55+
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
5656
if(wrapped_comp(first[i], val))
5757
{
5858
start = i + 1;
@@ -62,7 +62,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
6262
n = i;
6363
}
6464
} // end while
65-
65+
6666
return first + start;
6767
}
6868

@@ -94,7 +94,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
9494
Size start = 0, i;
9595
while(start < n)
9696
{
97-
i = (start + n) / 2;
97+
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
9898
if(wrapped_comp(val, first[i]))
9999
{
100100
n = i;
@@ -104,7 +104,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
104104
start = i + 1;
105105
}
106106
} // end while
107-
107+
108108
return first + start;
109109
}
110110

@@ -156,4 +156,3 @@ bool binary_search(RandomAccessIterator first, RandomAccessIterator last, const
156156
} // end thrust
157157

158158
#include <thrust/system/detail/generic/scalar/binary_search.inl>
159-

0 commit comments

Comments
 (0)