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?

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.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 14

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz