Why prefer start + (end - start) / 2 over (start + end) / 2 when calculating the middle of an array?

后端 未结 4 1580
时光说笑
时光说笑 2020-11-29 17:02

I\'ve seen programmers use the formula

mid = start + (end - start) / 2

instead of using the simpler formula

mid = (start +          


        
4条回答
  •  天命终不由人
    2020-11-29 17:55

    We can take a simple example to demonstrate this fact. Suppose in a certain large array, we are trying to find the midpoint of the range [1000, INT_MAX]. Now, INT_MAX is the largest value the int data type can store. Even if 1 is added to this, the final value will become negative.

    Also, start = 1000 and end = INT_MAX.

    Using the formula: (start + end)/2,

    the mid-point will be

    (1000 + INT_MAX)/2 = -(INT_MAX+999)/2, which is negative and may give segmentation fault if we try to index using this value.

    But, using the formula, (start + (end-start)/2), we get:

    (1000 + (INT_MAX-1000)/2) = (1000 + INT_MAX/2 - 500) = (INT_MAX/2 + 500) which will not overflow.

提交回复
热议问题