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

Commit

Permalink
Fix binary search middle calculation to avoid overflows
Browse files Browse the repository at this point in the history
  • Loading branch information
r-barnes authored and alliepiper committed Oct 14, 2020
1 parent 0203e9a commit 7749058
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions thrust/system/detail/generic/scalar/binary_search.inl
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
Size start = 0, i;
while(start < n)
{
i = (start + n) / 2;
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
if(wrapped_comp(first[i], val))
{
start = i + 1;
Expand All @@ -62,7 +62,7 @@ RandomAccessIterator lower_bound_n(RandomAccessIterator first,
n = i;
}
} // end while

return first + start;
}

Expand Down Expand Up @@ -94,7 +94,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
Size start = 0, i;
while(start < n)
{
i = (start + n) / 2;
i = start + (n - start) / 2; // Overflow-safe variant of (a+b)/2
if(wrapped_comp(val, first[i]))
{
n = i;
Expand All @@ -104,7 +104,7 @@ RandomAccessIterator upper_bound_n(RandomAccessIterator first,
start = i + 1;
}
} // end while

return first + start;
}

Expand Down Expand Up @@ -156,4 +156,3 @@ bool binary_search(RandomAccessIterator first, RandomAccessIterator last, const
} // end thrust

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

0 comments on commit 7749058

Please sign in to comment.