DEV Community

Discussion on: A bug was found in Java after almost 9 years of hiding.

Collapse
 
vinod12071 profile image
vinod12071

why dont we just have int mid = low/2 + high/2;

Collapse
 
damirtomic profile image
DamirTomic

Because that's wrong :D

low = 3;
high = 5;
int mid = 3/2 + 5/2 is actually 1 + 2 = 3 because division returns integers. And that gives the wrong result.
int mid =(low + high) / 2 = (3+5) / 2 = 8 / 2 = 4. This is the correct mid.