Explanation of the safe average of two numbers

前端 未结 7 1303
离开以前
离开以前 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 15:03

    The code you saw is broken: it doesn't compute the average of negative numbers correctly. If you are operating on non-negative values only, like indexes, that's OK, but it's not a general replacement. The code you have originally,

    int mid = low + ((high - low) / 2);
    

    isn't safe from overflow either because the difference high - low may overflow the range for signed integers. Again, if you only work with non-negative integers it's fine.

    Using the fact that A+B = 2*(A&B) + A^B we can compute the average of two integers without overflow like this:

    int mid = (high&low) + (high^low)/2;
    

    You can compute the division by 2 using a bit shift, but keep in mind the two are not the same: the division rounds towards 0 while the bit shift always rounds down.

    int mid = (high&low) + ((high^low)>>1);
    

提交回复
热议问题