Explanation of the safe average of two numbers

前端 未结 7 1307
离开以前
离开以前 2021-02-08 14:26

Whenever I need to average two numbers for an algorithm like binary search, I always do something like this:

int mid = low + ((high - low) / 2);
<
7条回答
  •  别跟我提以往
    2021-02-08 14:55

    The C++ version doesn't solve the overflow issue. It only solves the issue of successfully dividing by 2 using shift instead of /, an optimization that your compiler should be able to make itself if it would be a performance improvement.

    On the other hand overflow may not be a real problem, if your integral types are large enough to hold a reasonable range of indices.

提交回复
热议问题