Skip to content

Commit 42ac331

Browse files
committed
Renamed and fix overflow problem in binary search
1 parent 53bb529 commit 42ac331

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

algorithms/binary_search/binary_search.cpp renamed to algorithms/binary_search/find_closest/find_closest.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ size_t find_closest(const vector<int>& arr, const int search,
3131
}
3232

3333
// split array in half and recurse
34-
size_t middle = (begin + end) / 2;
34+
// (begin + end) / 2 could overflow
35+
size_t middle = begin + (end - begin) / 2;
3536
if (search < arr[middle]) {
3637
// recurse left
3738
return find_closest(arr, search, begin, middle);

0 commit comments

Comments
 (0)