The bug is that M = (L + U) / 2;
could lead to Integer overflow
The fix suggest using M = L + (U - L) / 2;
I found it much more intuitive to use M = L / 2 + U / 2;
as the fix which is mathematically equivalent to M = L + (U - L) / 2
: (see the derivation below).
The derivation:
M = L + (U - L) / 2;
M = L + U / 2 - L / 2;
M = L - L / 2 + U / 2;
M = L / 2 + U / 2;
So is there any specific reason to write M = L + (U - L) / 2;
as the fix?