Algorithms and Data Structures · Middle · Question 14 of 75
Why is mid = lo + Math.floor((hi - lo) / 2) recommended in many languages instead of (lo + hi) / 2?
- ✓Correct answer:
lo + hican overflow a fixed-size integer - 2Division is slower than subtraction
- 3The first form is always rounded up
Explanation
In Java or C++ with 32-bit ints, lo + hi can exceed the maximum and become negative. JavaScript numbers are doubles, so this isn't a practical issue for array indices, but the habit is worth knowing.