Skip to content

Commit dc9501d

Browse files
authored
Avoids Overflow Errors common in Binary search
Adding two large integers then dividing the sum, (a+b)/2 ,might end up creating a sum that can't fit in memory. However this overflow can be avoided by never adding the numbers first instead, adding the difference of the two numbers to the least i.e (a+b)/2 == a+(b-a)/2 == b-(b-a)/2 ... Please comment or ask for further clarification instead of just rejecting the proposal. Thanks
1 parent eab0494 commit dc9501d

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

searches/binary_search.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ func binarySearch(array []int, target int, lowIndex int, highIndex int) int {
77
if highIndex < lowIndex {
88
return -1
99
}
10-
mid := int((lowIndex + highIndex) / 2)
10+
mid := int(lowIndex + (highIndex-lowIndex)/2)
1111
if array[mid] > target {
1212
return binarySearch(array, target, lowIndex, mid)
1313
} else if array[mid] < target {
@@ -22,7 +22,7 @@ func iterBinarySearch(array []int, target int, lowIndex int, highIndex int) int
2222
endIndex := highIndex
2323
var mid int
2424
for startIndex < endIndex {
25-
mid = int((startIndex + endIndex) / 2)
25+
mid = int(startIndex + (endIndex-startIndex))
2626
if array[mid] > target {
2727
endIndex = mid
2828
} else if array[mid] < target {

0 commit comments

Comments
 (0)