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 the following implementation of the Binary Search function:
#include <iostream> // Binary search function int binarySearch( int arr[], int low, int high, int x) {
// Continue searching while the low index is less than or equal to high index
while (low <= high) {
// Find the middle index
int mid = (low + high) / 2;
// If the element is present at the middle
if (arr[mid] == x)
return mid;
// If x is greater, ignore left half
else if (arr[mid] < x)
low = mid + 1;
// If x is smaller, ignore right half
else
high = mid - 1;
}
// If the element is not present
return -1;
} int main() {
// Sorted array
int arr[] = {2, 3, 4, 10, 40};
// Element to be searched
int x = 10;
// Perform binary search
int result = binarySearch(arr, 0, sizeof (arr) / sizeof (arr[0]) - 1, x);
// Display the result
if (result != -1)
std::cout << "Element " << x << " is present at index " << result << std::endl;
else
std::cout << "Element " << x << " is not present in the array" << std::endl;
return 0;
} |
// A iterative binary search function. It returns location // of x in given array arr[l..r] if present, otherwise -1 int binarySearch( int arr[], int low, int high, int x)
{ while (low <= high) {
// Find index of middle element
int mid = (low + high) / 2;
// Check if x is present at mid
if (arr[mid] == x)
return mid;
// If x greater, ignore left half
if (arr[mid] <= x)
low = mid + 1;
// If x is smaller, ignore right half
else
high = mid - 1;
}
// If we reach here, then element was not present
return -1;
} |
// An iterative binary search function. It returns the location // of x in the given array arr[l..r] if present, otherwise -1. public static int binarySearch( int [] arr, int low, int high, int x) {
while (low <= high) {
// Find the index of the middle element
int mid = (low + high) / 2 ;
// Check if x is present at mid
if (arr[mid] == x)
return mid;
// If x is greater, ignore the left half
if (arr[mid] < x)
low = mid + 1 ;
// If x is smaller, ignore the right half
else
high = mid - 1 ;
}
// If we reach here, then the element was not present
return - 1 ;
} |
# An iterative binary search function. # It returns the location of x in the given array arr[l..r] if present, otherwise -1. def binary_search(arr, low, high, x):
while low < = high:
# Find the index of the middle element
mid = (low + high) / / 2
# Check if x is present at mid
if arr[mid] = = x:
return mid
# If x is greater, ignore the left half
elif arr[mid] < x:
low = mid + 1
# If x is smaller, ignore the right half
else :
high = mid - 1
# If we reach here, then the element was not present
return - 1
# Example usage arr = [ 2 , 3 , 4 , 10 , 40 ]
x = 10
# Perform binary search result = binary_search(arr, 0 , len (arr) - 1 , x)
# Display the result if result ! = - 1 :
print (f "Element {x} is present at index {result}" )
else :
print (f "Element {x} is not present in the array" )
|
using System;
class Program
{ // Binary search function
static int BinarySearch( int [] arr, int low, int high, int x)
{
// Continue searching while the low index is less than or equal to high index
while (low <= high)
{
// Find the middle index
int mid = (low + high) / 2;
// If the element is present at the middle
if (arr[mid] == x)
return mid;
// If x is greater, ignore left half
else if (arr[mid] < x)
low = mid + 1;
// If x is smaller, ignore right half
else
high = mid - 1;
}
// If element is not present
return -1;
}
static void Main()
{
// Sorted array
int [] arr = { 2, 3, 4, 10, 40 };
// Element to be searched
int x = 10;
// Perform binary search
int result = BinarySearch(arr, 0, arr.Length - 1, x);
// Display the result
if (result != -1)
Console.WriteLine($ "Element {x} is present at index {result}" );
else
Console.WriteLine($ "Element {x} is not present in the array" );
}
} |
// An iterative binary search function. It returns the location // of x in the given array arr[l..r] if present, otherwise -1. function binarySearch(arr, low, high, x) {
while (low <= high) {
// Find the index of the middle element
let mid = Math.floor((low + high) / 2);
// Check if x is present at mid
if (arr[mid] === x)
return mid;
// If x is greater, ignore the left half
if (arr[mid] < x)
low = mid + 1;
// If x is smaller, ignore the right half
else
high = mid - 1;
}
// If we reach here, then the element was not present
return -1;
} |
The above code looks fine except for one subtle thing, the expression
mid = (low + high)/2.
It fails for large values of low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive value of int data type (i.e., 231 – 1). The sum overflows to a negative value, and the value stays negative when divided by two. This causes an array index out of bounds with unpredictable results.
What is the correct way to calculate “mid” in Binary Search Algorithm?
The following is one way:
int mid = low + ((high – low) / 2);
Probably faster, and arguably as clear is (works only in Java, refer this):
int mid = (low + high) >>> 1;
In C and C++ (where you don’t have the >>> operator), you can do this:
mid = ((unsigned int)low + (unsigned int)high)) >> 1
A similar problem appears in other similar types of divide and conquer algorithms like Merge Sort as well. The above problem occurs when values of low and high are such that their sum is greater than the permissible limit of the data type. Although, this much size of an array is not likely to appear most of the time.