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
Minimum steps to reach end from start by performing multiplication and mod operations with array elements
Given start, end and an array of N numbers. At each step, start is multiplied with any number in the array and then mod operation with 100000 is done to get the new start. The task is to find the minimum steps in which end can be achieved starting from start. Examples: Input: start = 3 end = 30 a[]
15+ min read
Count minimum number of moves to front or end to sort an array
Given an array arr[] of size N, the task is to find the minimum moves to the beginning or end of the array required to make the array sorted in non-decreasing order. Examples: Input: arr[] = {4, 7, 2, 3, 9} Output: 2 Explanation: Perform the following operations: Step 1: Move the element 3 to the st
15+ min read
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} Is this method to find mid always correct in Binary Search? Consider th
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
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
Sort Array such that smallest is at 0th index and next smallest it at last index and so on
Given an array, arr[] of N integers, the task is to rearrange the array elements such that the smallest element is at the 0th position, the second smallest element is at the (N-1)th position, the third smallest element at 1st position, 4th smallest element is at the (N-2)th position, and so on for a
12 min read
Find start and ending index of an element in an unsorted array
Given an array of integers, task is to find the starting and ending position of a given key. Examples: Input : arr[] = {1, 2, 3, 4, 5, 5} Key = 5Output : Start index: 4 Last index: 5Explanation: Starting index where 5is present is 4 and ending index is 5. Input :arr[] = {1, 3, 7, 8, 6}, Key = 2Outpu
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
Find index of an extra element present in one sorted array
Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element. Examples: Input: {2, 4, 6, 8, 9, 10, 12}; {2, 4, 6, 8, 10, 12}; Output: 4 Explanation: The first array has an extra element 9. The extr
15+ min read