Why start + (end - start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?
Last Updated :
21 Apr, 2024
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();
Outputstart = 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]);
}
}
Python3
class Main:
@staticmethod
def main():
s = 2
e = 3
start = [s]
end = [e]
mid = [start[0] + (end[0] - start[0]) // 2]
# Output
print("Start:", start[0])
print("End:", end[0])
print("Mid:", mid[0])
# Run the main method
Main.main()
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);
OutputStart: 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();
Outputstart = 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 [email protected]. 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.
Similar Reads
How to calculate "mid" or Middle Element Index in Binary Search?
The most common method to calculate mid or middle element index in Binary Search Algorithm is to find the middle of the highest index and lowest index of the searchable space, using the formula mid = low + \frac{(high - low)}{2} Finding the middle index "mid" in Binary Search AlgorithmIs this method
6 min read
Minimum steps required to reach the end of Array with a given capacity
Given an array arr[] of size n. You will have to traverse the array from left to right deducting each element of the array from the initial capacity, such that your initial capacity should never go below 0. In case, the current capacity is less than the current element, we can traverse back to the s
15 min read
Check if the sum of a subarray within a given range is a perfect square or not
Given an array arr[] of size N and an array range[], the task is to check if the sum of the subarray {range[0], .. , range[1]} is a perfect square or not. If the sum is a perfect square, then print the square root of the sum. Otherwise, print -1. Example : Input: arr[] = {2, 19, 33, 48, 90, 100}, ra
7 min read
Divide a sorted array in K parts with sum of difference of max and min minimized in each part - Set 2
Given an ascending sorted array arr[] of size N and an integer K, the task is to partition the given array into K non-empty subarrays such that the sum of differences of the maximum and the minimum of each subarray is minimized. Examples: Input: arr[] = { 10, 20, 70, 80 }, N = 4, K = 2Output: 20Expl
11 min read
Find the Middle Element of an Array or List
Given an array or a list of elements. The task is to find the middle element of given array or list of elements. If the array size is odd, return the single middle element. If the array size is even, return the two middle elements. ExampleInput: arr = {1, 2, 3, 4, 5}Output: 3 Input: arr = {7, 8, 9,
9 min read
Minimize cost to reach end of an array by two forward jumps or one backward jump in each move
Given an array arr[] consisting of N positive integers, the task is to find the minimum cost required to either cross the array or reach the end of the array by only moving to indices (i + 2) and (i - 1) from the ith index. Examples: Input: arr[] = {5, 1, 2, 10, 100}Output: 18Explanation:Optimal cos
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C++ // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int b
11 min read
Rearrange the Array by shifting middle elements to start and end alternatively
Given an array, the task is to shift the middle element to the start and end of the array alternatively, till the middle element becomes equal to the first element of the original array. Input: arr[]=[2, 8, 5, 9, 10]Output: [9, 5, 2, 10, 8]Explanation: We can get this output by shifting middle eleme
13 min read
Count distinct median possible for an Array using given ranges of elements
Given an array of pairs arr[] which denotes the ranges of the elements of an array, the task is to count the distinct median of every possible array using these ranges. Examples: Input: arr[] = {{1, 2}, {2, 3}} Output: 3 Explanation: => If x1 = 1 and x2 = 2, Median is 1.5 => If x1 = 1 and x2 =
8 min read
Why is it faster to process sorted array than an unsorted array ?
Here is a C++ and java code that illustrates that sorting the data miraculously makes the code faster than the unsorted version. Let's try out sample C++ and java programs to understand the problem statement better. Implementation: CPP // CPP program to demonstrate processing // time of sorted and u
6 min read