The Ubiquitous Binary Search | Set 1
Last Updated :
07 May, 2024
We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, “I sincerely attempt to solve the problem and ensure there are no corner cases”. After reading each problem, minimize the browser and try solving it.Â
Problem Statement: Given a sorted array of N distinct elements, find a key in the array using the least number of comparisons. (Do you think binary search is optimal to search a key in sorted array?) Without much theory, here is typical binary search algorithm.Â
C++
// Returns location of key, or -1 if not found
int BinarySearch(int A[], int l, int r, int key){
int m;
while( l <= r ){
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
C
// Returns location of key, or -1 if not found
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l <= r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
Java
// Java code to implement the approach
import java.util.*;
class GFG {
// Returns location of key, or -1 if not found
static int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l < r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
}
// This code is contributed by sanjoy_62.
Python
# Returns location of key, or -1 if not found
def BinarySearch(A, l, r, key):
while (l < r):
m = l + (r - l) // 2
if A[m] == key: #first comparison
return m
if A[m] < key: # second comparison
l = m + 1
else:
r = m - 1
return -1
""" This code is contributed by Rajat Kumar """
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Returns location of key, or -1 if not found
static int BinarySearch(int[] A, int l, int r, int key)
{
int m;
while( l < r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
}
// This code is contributed by code_hunt.
Javascript
<script>
// Javascript code to implement the approach
// Returns location of key, or -1 if not found
function BinarySearch(A, l, r, key) {
let m;
while (l < r) {
m = l + (r - l) / 2;
if (A[m] == key) // first comparison
return m;
if (A[m] < key) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
// This code is contributed by gfgking
</script>
Theoretically we need log N + 1 comparisons in worst case. If we observe, we are using two comparisons per iteration except during final successful match, if any. In practice, comparison would be costly operation, it won’t be just primitive type comparison. It is more economical to minimize comparisons as that of theoretical limit. See below figure on initialize of indices in the next implementation. Â
The following implementation uses fewer number of comparisons.Â
C++
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
//this code is contributed by aditya942003patil
C
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
Java
// Java function for above algorithm
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l k > 1 )
{
m = l + k(r - l)/2;
if( A[m]k <= key )
l = km;
elsek
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
//this code is contributed by Akshay Tripathi(akshaytripathi630)
Python
# Invariant: A[l] <= key and A[r] > key
# Boundary: |r - l| = 1
# Input: A[l .... r-1]
def BinarySearch(A, l, r, key):
while (r-l > 1):
m = l+(r-l)//2
if A[m] <= key:
l = m
else:
r = m
if A[l] == key:
return l
if A[r] == key:
return r
return -1
""" Code is written by Rajat Kumar"""
C#
// C# conversion
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
if (A[l] == key)
return l;
if (A[r] == key)
return r;
else
return -1;
}
// This code is contributed by akashish__
Javascript
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
function BinarySearch(A, l, r, key)
{
let m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
In the while loop we are depending only on one comparison. The search space converges to place l and r point two different consecutive elements. We need one more comparison to trace search status. You can see sample test case http://ideone.com/76bad0. (C++11 code)Â
Problem Statement: Given an array of N distinct integers, find floor value of input ‘key’. Say, A = {-1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome. We can use the above optimized implementation to find floor value of key. We keep moving the left pointer to right most as long as the invariant holds. Eventually left pointer points an element less than or equal to key (by definition floor value). The following are possible corner cases, —> If all elements in the array are smaller than key, left pointer moves till last element. —> If all elements in the array are greater than key, it is an error condition. —> If all elements in the array equal and <= key, it is worst case input to our implementation.Â
Here is implementation,Â
C++
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
int Floor(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return A[l];
}
// Initial call
int Floor(int A[], int size, int key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
//this code is contributed by aditya942003patil
C
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
int Floor(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return A[l];
}
// Initial call
int Floor(int A[], int size, int key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
Java
public class Floor {
// This function returns the largest value in A that is
// less than or equal to key. Invariant: A[l] <= key and
// A[r] > key Boundary: |r - l| = 1 Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
static int floor(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
return A[l];
}
// Initial call
static int floor(int[] A, int size, int key)
{
// Add error checking if key < A[0]
if (key < A[0])
return -1;
// Observe boundaries
return floor(A, 0, size, key);
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(floor(arr, arr.length - 1, 3));
}
}
Python
# largest value <= key
# Invariant: A[l] <= key and A[r] > key
# Boundary: |r - l| = 1
# Input: A[l .... r-1]
# Precondition: A[l] <= key <= A[r]
def Floor(A,l,r,key):
while (r-l>1):
m=l+(r-l)//2
if A[m]<=key:
l=m
else:
r=m
return A[l]
# Initial call
def Floor(A,size,key):
# Add error checking if key < A[0]
if key<A[0]:
return -1
# Observe boundaries
return Floor(A,0,size,key)
"""Code is written by Rajat Kumar"""
C#
using System;
public class Floor {
// This function returns the largest value in A that is
// less than or equal to key. Invariant: A[l] <= key and
// A[r] > key Boundary: |r - l| = 1 Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
static int floor(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
return A[l];
}
// Initial call
static int floor(int[] A, int size, int key)
{
// Add error checking if key < A[0]
if (key < A[0])
return -1;
// Observe boundaries
return floor(A, 0, size, key);
}
public static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(floor(arr, arr.Length - 1, 3));
}
}
// This code is contributed by sarojmcy2e
Javascript
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
function Floor(A, l, r, key){
let m;
while(r - l > 1){
m = l + parseInt((r-l)/2);
if(A[m] <= key) l = m;
else r = m;
}
return A[l];
}
// Initial call
function Floor(A, size, key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGAWRAL2852002)
You can see some test cases http://ideone.com/z0Kx4a.Â
Problem Statement: Given a sorted array with possible duplicate elements. Find number of occurrences of input ‘key’ in log N time. The idea here is finding left and right most occurrences of key in the array using binary search. We can modify floor function to trace right most occurrence and left most occurrence.Â
Here is implementation,Â
C++
#include <iostream>
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
int GetRightPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
int GetLeftPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] >= key )
r = m;
else
l = m;
}
return r;
}
int CountOccurrences(int A[], int size, int key)
{
// Observe boundary conditions
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
// What if the element doesn't exists in the array?
// The checks helps to trace that element exists
return (A[left] == key && key == A[right])?
(right - left + 1) : 0;
}
int main()
{
int A[] = {1, 1, 2, 3, 3, 3, 3, 3, 4, 4, 5};
int size = sizeof(A) / sizeof(A[0]);
int key = 3;
std::cout << "Number of occurances of " << key << ": " << CountOccurances(A, size, key) << std::endl;
return 0;
}
//code is written by khushboogoyal499
C
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
int GetRightPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
int GetLeftPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] >= key )
r = m;
else
l = m;
}
return r;
}
int CountOccurrences(int A[], int size, int key)
{
// Observe boundary conditions
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
// What if the element doesn't exists in the array?
// The checks helps to trace that element exists
return (A[left] == key && key == A[right])?
(right - left + 1) : 0;
}
Java
public class OccurrencesInSortedArray {
// Returns the index of the leftmost occurrence of the
// given key in the array
private static int getLeftPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (arr[mid] >= key) {
right = mid;
}
else {
left = mid;
}
}
return right;
}
// Returns the index of the rightmost occurrence of the
// given key in the array
private static int getRightPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (arr[mid] <= key) {
left = mid;
}
else {
right = mid;
}
}
return left;
}
// Returns the count of occurrences of the given key in
// the array
public static int countOccurrences(int[] arr, int key)
{
int left
= getLeftPosition(arr, -1, arr.length - 1, key);
int right
= getRightPosition(arr, 0, arr.length, key);
if (arr[left] == key && key == arr[right]) {
return right - left + 1;
}
return 0;
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 2, 2, 3, 4, 4, 5, 5 };
int key = 2;
System.out.println(
countOccurrences(arr, key)); // Output: 3
}
}
Python
# Input: Indices Range [l ... r)
# Invariant: A[l] <= key and A[r] > key
def GetRightPosition(A,l,r,key):
while r-l>1:
m=l+(r-l)//2
if A[m]<=key:
l=m
else:
r=m
return l
# Input: Indices Range (l ... r]
# Invariant: A[r] >= key and A[l] > key
def GetLeftPosition(A,l,r,key):
while r-l>1:
m=l+(r-l)//2
if A[m]>=key:
r=m
else:
l=m
return r
def countOccurrences(A,size,key):
#Observe boundary conditions
left=GetLeftPosition(A,-1,size-1,key)
right=GetRightPosition(A,0,size,key)
# What if the element doesn't exists in the array?
# The checks helps to trace that element exists
if A[left]==key and key==A[right]:
return right-left+1
return 0
"""Code is written by Rajat Kumar"""
C#
using System;
public class OccurrencesInSortedArray
{
// Returns the index of the leftmost occurrence of the
// given key in the array
private static int getLeftPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1)
{
int mid = left + (right - left) / 2;
if (arr[mid] >= key)
{
right = mid;
}
else
{
left = mid;
}
}
return right;
}
// Returns the index of the rightmost occurrence of the
// given key in the array
private static int getRightPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1)
{
int mid = left + (right - left) / 2;
if (arr[mid] <= key)
{
left = mid;
}
else
{
right = mid;
}
}
return left;
}
// Returns the count of occurrences of the given key in
// the array
public static int countOccurrences(int[] arr, int key)
{
int left = getLeftPosition(arr, -1, arr.Length - 1, key);
int right = getRightPosition(arr, 0, arr.Length, key);
if (arr[left] == key && key == arr[right])
{
return right - left + 1;
}
return 0;
}
public static void Main(string[] args)
{
int[] arr = { 1, 2, 2, 2, 3, 4, 4, 5, 5 };
int key = 2;
Console.WriteLine(countOccurrences(arr, key)); // Output: 3
}
}
Javascript
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
function getRightPosition(A, l, r, key) {
while (r - l > 1) {
const m = l + Math.floor((r - l) / 2);
if (A[m] <= key) {
l = m;
} else {
r = m;
}
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
function getLeftPosition(A, l, r, key) {
while (r - l > 1) {
const m = l + Math.floor((r - l) / 2);
if (A[m] >= key) {
r = m;
} else {
l = m;
}
}
return r;
}
function countOccurrences(A, size, key) {
// Observe boundary conditions
let left = getLeftPosition(A, -1, size - 1, key);
let right = getRightPosition(A, 0, size, key);
// What if the element doesn't exist in the array?
// The checks help to determine whether the element exists
if (A[left] === key && key === A[right]) {
return right - left + 1;
}
return 0;
}
// Example usage
const A = [1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6];
const key = 4;
const size = A.length;
const occurrences = countOccurrences(A, size, key);
console.log(`The number of occurrences of ${key} is: ${occurrences}`);
Sample code http://ideone.com/zn6R6a.Â
Problem Statement: Given a sorted array of distinct elements, and the array is rotated at an unknown position. Find minimum element in the array. We can see  pictorial representation of sample input array in the below figure. Â
We converge the search space till l and r points single element. If the middle location falls in the first pulse, the condition A[m] < A[r] doesn’t satisfy, we converge our search space to A[m+1 … r]. If the middle location falls in the second pulse, the condition A[m] < A[r] satisfied, we converge our search space to A[1 … m]. At every iteration we check for search space size, if it is 1, we are done.Â
Given below is implementation of algorithm. Can you come up with different implementation?Â
C++
int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if( A[l] >= A[r] )
return l;
while( l <= r )
{
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if( l == r )
return l;
m = l + (r-l)/2; // 'm' can fall in first pulse,
// second pulse or exactly in the middle
if( A[m] < A[r] )
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
else
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
return -1;
}
int BinarySearchIndexOfMinimumRotatedArray(int A[], int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
//this code is contributed by aditya942003patil
C
int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if( A[l] <= A[r] )
return l;
while( l <= r )
{
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if( l == r )
return l;
m = l + (r-l)/2; // 'm' can fall in first pulse,
// second pulse or exactly in the middle
if( A[m] < A[r] )
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
else
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
return -1;
}
int BinarySearchIndexOfMinimumRotatedArray(int A[], int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
Java
public static int binarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if (A[l] >= A[r]) {
return l;
}
while (l <= r) {
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if (l == r) {
return l;
}
m = l + (r - l) / 2;
if (A[m] < A[r]) {
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
} else {
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m + 1;
}
}
return -1;
}
public static int binarySearchIndexOfMinimumRotatedArray(int A[], int size) {
return binarySearchIndexOfMinimumRotatedArray(A, 0, size - 1);
}
Python
def BinarySearchIndexOfMinimumRotatedArray(A, l, r):
# extreme condition, size zero or size two
# Precondition: A[l] > A[r]
if A[l] >= A[r]:
return l
while (l <= r):
# Termination condition (l will eventually falls on r, and r always
# point minimum possible value)
if l == r:
return l
m = l+(r-l)//2 # 'm' can fall in first pulse,
# second pulse or exactly in the middle
if A[m] < A[r]:
# min can't be in the range
# (m < i <= r), we can exclude A[m+1 ... r]
r = m
else:
# min must be in the range (m < i <= r),
# we must search in A[m+1 ... r]
l = m+1
return -1
def BinarySearchIndexOfMinimumRotatedArray(A, size):
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1)
"""Code is written by Rajat Kumar"""
C#
using System;
public class Program
{
public static int BinarySearchIndexOfMinimumRotatedArray(int[] A, int l, int r)
{
// Extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if (A[l] >= A[r])
{
return l;
}
while (l <= r)
{
// Termination condition (l will eventually fall on r, and r always
// points to the minimum possible value)
if (l == r)
{
return l;
}
m = l + (r - l) / 2;
if (A[m] < A[r])
{
// Minimum can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
}
else
{
// Minimum must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m + 1;
}
}
return -1;
}
public static int BinarySearchIndexOfMinimumRotatedArray(int[] A, int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size - 1);
}
public static void Main()
{
int[] A = { 6, 7, 8, 9, 1, 2, 3, 4, 5 };
int size = A.Length;
int minIndex = BinarySearchIndexOfMinimumRotatedArray(A, size);
Console.WriteLine("The index of the minimum element in the rotated array is: " + minIndex);
}
}
Javascript
function BinarySearchIndexOfMinimumRotatedArray(A, l, r){
// extreme condition, size zero or size two
let m;
// Precondition: A[l] > A[r]
if(A[l] <= A[r]) return l;
while(l <= r){
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if(l == r) return l;
m = l + (r-l)/2;
if(A[m] < A[r]){
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
}else{
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
}
return -1;
}
function BinarySearchIndexOfMinimumRotatedArray(A, size){
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
See sample test cases http://ideone.com/KbwDrk.Â
Exercises:Â
1. A function called signum(x, y)Â is defined as,
signum(x, y) = -1 if x < y
= 0 if x = y
= 1 if x > y
Did you come across any instruction set in which a comparison behaves like signum function? Can it make the first implementation of binary search optimal?Â
2. Implement ceil function replica of floor function.Â
3. Discuss with your friends “Is binary search optimal (results in the least number of comparisons)? Why not ternary search or interpolation search on a sorted array? When do you prefer ternary or interpolation search over binary search?”Â
4. Draw a tree representation of binary search (believe me, it helps you a lot to understand much internals of binary search).
Stay tuned, I will cover few more interesting problems using binary search in upcoming articles. I welcome your comments. – – – by Venki.
Please Login to comment...