Why start + (end – start)/2 is preferable method for calculating middle of an array?
3938
Aug 08, 2023

Why start + (end – start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?

The reason for using the expression mid = start + (end - start) / 2 instead of mid = (start + end) / 2 when calculating the middle index in binary search or other similar algorithms is to prevent integer overflow.

In programming, integers have a limited range that they can represent due to memory constraints. When you add two large integers together, there's a possibility that the result might exceed the maximum value that can be represented, causing an integer overflow. This can lead to unexpected and incorrect behavior in your program.

By using the expression mid = start + (end - start) / 2, you are essentially calculating the middle index while avoiding the direct addition of start and end, which can help prevent integer overflow. The subtraction end - start ensures that the difference is calculated before any addition is done, reducing the chance of overflow.
However, it's important to note that in many programming languages and environments, integer overflow might not be a common concern or may be handled implicitly. For instance, modern programming languages and platforms might automatically handle overflow by wrapping around or throwing exceptions. Still, using the safer expression helps in scenarios where you might be working with large numbers or in environments where overflow handling is not as automatic or safe.

In summary, while both expressions might work in many cases, using mid = start + (end - start) / 2 is a safer practice to prevent potential integer overflow, especially when dealing with larger values.

// C++ program for calculating mid of array
#include <bits/stdc++.h>
using namespace std;
 
// driver program
int main(){
    int start = INT_MAX, end = INT_MAX;
      cout<<"start = "<<start<<endl;
      cout<<"end = "<<end<<endl;
 
    // method 1
    int mid1 = (start + end) / 2;
      cout<<"mid using (start + end)/2 = "<<mid1<<endl;
 
    // method 2
    int mid2 = start + (end - start) / 2;
      cout<<"mid using start + (end - start)/2 = "<<mid2<<endl;
    return 0;
}
Output: 

start = 2147483647
end = 2147483647
mid using (start + end)/2 = -1
mid using start + (end - start)/2 = 2147483647
Comments (17)