Open In App

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

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end – start)/2 over (start + end)/2, which are described below :

The very first way of finding middle index is 

mid = (start + end)/2

But there is a problem with this approach, what if the value of start or end or both is INT_MAX, it will cause integer overflow.
The better way of calculating mid-index is : 

mid = start + (end - start)/2        //mid-index

Let’s try these both methods in different programming languages :  

C++
// 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;
}
C
// program for calculating mid of array
#include <stdio.h>
#include <limits.h>
int main()
{
    int start = INT_MAX, end = INT_MAX;
    printf("start = %dn", start);
    printf("end = %dn", end);

    // method 1
    int mid1 = (start + end) / 2;
    printf("mid using (start + end)/2 = %dn", mid1);

    // method 2
    int mid2 = start + (end - start) / 2;
    printf("mid using start + (end - start)/2 = %dn", mid2);
    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;

class GFG {
    public static void main (String[] args) {
        int start = Integer.MAX_VALUE;
        int end = Integer.MAX_VALUE;
        
        System.out.println("start = " + start);
        System.out.println("end = " + end);
        
        // Method 1
        int mid1 = (start + end) / 2;
        System.out.println("mid using (start + end) / 2 = " + mid1);
        
        // Method 2
        int mid2 = start + (end - start) / 2;
        System.out.println("mid using start + (end - start) / 2 = " + mid2);

    }
}
Python3
# Function to find the midpoint using two different methods
def find_midpoint(start, end):
    print("start =", start)
    print("end =", end)

    # Method 1: Using (start + end) / 2
    mid1 = (start + end) // 2  # Using integer division to ensure the result is an integer
    print("mid using (start + end) / 2 =", mid1)

    # Method 2: Using start + (end - start) / 2
    mid2 = start + (end - start) // 2  # Using integer division to ensure the result is an integer
    print("mid using start + (end - start) / 2 =", mid2)

# Main function
def main():
    start = 2147483647  # Maximum value for int in Python
    end = 2147483647  # Maximum value for int in Python
    find_midpoint(start, end)

# Execute main function
if __name__ == "__main__":
    main()
C#
using System;

class Program
{
    static void Main()
    {
        int start = int.MaxValue, end = int.MaxValue;
        Console.WriteLine("start = " + start);
        Console.WriteLine("end = " + end);

        // method 1
        int mid1 = (start + end) / 2;
        Console.WriteLine("mid using (start + end)/2 = " + mid1);

        // method 2
        int mid2 = start + (end - start) / 2;
        Console.WriteLine("mid using start + (end - start)/2 = " + mid2);
    }
}
// This code is contributed by Yash Agarwal(yashagarwal2852002)
JavaScript
// JavaScript program for calculating mid of array

// Driver program
function main() {
  let start = 2147483647;
  let end = 2147483647;

  console.log("start = " + start);
  console.log("end = " + end);

  // method 1
  let mid1 = Math.floor((start + end) / 2);
  console.log("mid using (start + end)/2 = " + mid1);

  // method 2
  let mid2 = start + Math.floor((end - start) / 2);
  console.log("mid using start + (end - start)/2 = " + mid2);
}

// Calling the main function
main();

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


The time complexity of this program is O(1) as it only performs a fixed number of arithmetic operations and print statements, regardless of the input size.

The space complexity of this program is also O(1) as it only uses a fixed number of integer variables and constant string literals for the print statements, regardless of the input size.

Note : (end – start) may overflow if end < 0 or start < 0
If you see the output, by using second method you get correct output and first method fails to calculate mid and if you use this index (-1 in this case), it can cause segmentation fault because of invalid index of array.

start + (end – start)/2 also works even if you are using pointers : 

Example : 
Method 1  

C++
#include <iostream>

int main() {
    int s = 2, e = 3;
    int* start = &s;
    int* end = &e;
    int* mid = start + (end - start) / 2;
    
    // Output
    std::cout << "Start: " << *start << std::endl;
    std::cout << "End: " << *end << std::endl;
    std::cout << "Mid: " << *mid << std::endl;

    return 0;
}
C
#include <stdio.h>

int main() {
    int s = 2, e = 3;
    int* start = &s;
    int* end = &e;
    int* mid = start + (end - start) / 2;
    
    // Output
    printf("Start: %d\n", *start);
    printf("End: %d\n", *end);
    printf("Mid: %d\n", *mid);

    return 0;
}
Java
public class Main {
    public static void main(String[] args) {
        int s = 2, e = 3;
        int[] start = new int[]{s};
        int[] end = new int[]{e};
        int[] mid = new int[]{start[0] + (end[0] - start[0]) / 2};

        // Output
        System.out.println("Start: " + start[0]);
        System.out.println("End: " + end[0]);
        System.out.println("Mid: " + mid[0]);
    }
}
JavaScript
let s = 2, e = 3;
let start = s;
let end = e;
let mid = Math.floor((start + end) / 2);

// Output
console.log("Start: " + start);
console.log("End: " + end);
console.log("Mid: " + mid);

Output
Start: 2
End: 3
Mid: 2

Output : 

error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’
int *mid = (start + end)/2;

Method 2  

C++
#include <iostream>

int main() {
    // Initializing start and end pointers
    int s = 2, e = 3;
    int* start = &s;
    int* end = &e;

    // Calculating mid pointer using pointer arithmetic
    int* mid = start + (end - start) / 2;

    // Displaying the values
    std::cout << "start = " << *start << std::endl;
    std::cout << "end = " << *end << std::endl;
    std::cout << "mid = " << *mid << std::endl;

    return 0;
}
C
int s = 2, e = 3;
int* start = &s;
int* end = &e;
int* mid = start + (end - start) / 2;
Java
public class Main {
    public static void main(String[] args) {
        // Initializing start and end pointers
        int s = 2, e = 3;
        int[] start = {s};
        int[] end = {e};

        // Calculating mid pointer using pointer arithmetic
        int[] mid = {start[0] + (end[0] - start[0]) / 2};

        // Displaying the values
        System.out.println("start = " + start[0]);
        System.out.println("end = " + end[0]);
        System.out.println("mid = " + mid[0]);
    }
}
//this code is contributed by Monu.
Python
# Initializing start and end pointers
s = 2
e = 3
start = s
end = e

# Calculating mid pointer
mid = start + (end - start) // 2

# Displaying the values
print("start =", start)
print("end =", end)
print("mid =", mid)
#this code is contributed by monu.
C#
using System;

class Program
{
    static void Main()
    {
        // Initializing start and end pointers
        int s = 2;
        int e = 3;

        // Initializing start and end pointers
        int start = s;
        int end = e;

        // Calculating mid pointer
        int mid = start + (end - start) / 2;

        // Displaying the values
        Console.WriteLine("start = " + start);
        Console.WriteLine("end = " + end);
        Console.WriteLine("mid = " + mid);
    }
}
JavaScript
// Main function
function main() {
    // Initializing start and end pointers
    let s = 2, e = 3;
    let start = [s];
    let end = [e];

    // Calculating mid pointer using pointer arithmetic
    let mid = [start[0] + (end[0] - start[0]) / 2];

    // Displaying the values
    console.log("start = " + start[0]);
    console.log("end = " + end[0]);
    console.log("mid = " + mid[0]);
}

// Call the main function
main();

Output
start = 2
end = 3
mid = 2


Explanation: pointer addition is not supported in C while pointer subtraction is supported, the reason being the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H)(in short subtraction gives memory distance), but addition of two pointers in not meaningful, that’s why not supported

References : 
1) Additive Operators: + and – 
2) why-prefer-start-end-start-2-over-start-end-2-when-calculating-the 
3) pointer-addition-vs-subtraction

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads