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++
int BinarySearch( int A[], int l, int r, int key){
int m;
while ( l <= r ){
m = l + (r-l)/2;
if ( A[m] == key )
return m;
if ( A[m] < key )
l = m + 1;
else
r = m - 1;
}
return -1;
}
|
C
int BinarySearch( int A[], int l, int r, int key)
{
int m;
while ( l <= r )
{
m = l + (r-l)/2;
if ( A[m] == key )
return m;
if ( A[m] < key )
l = m + 1;
else
r = m - 1;
}
return -1;
}
|
Java
import java.util.*;
class GFG {
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 )
return m;
if ( A[m] < key )
l = m + 1 ;
else
r = m - 1 ;
}
return - 1 ;
}
}
|
Python3
def BinarySearch(A, l, r, key):
while (l < r):
m = l + (r - l) / / 2
if A[m] = = key:
return m
if A[m] < key:
l = m + 1
else :
r = m - 1
return - 1
|
C#
using System;
class GFG
{
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 )
return m;
if ( A[m] < key )
l = m + 1;
else
r = m - 1;
}
return -1;
}
}
|
Javascript
<script>
function BinarySearch(A, l, r, key) {
let m;
while (l < r) {
m = l + (r - l) / 2;
if (A[m] == key)
return m;
if (A[m] < key)
l = m + 1;
else
r = m - 1;
}
return -1;
}
</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++
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;
}
|
C
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
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 ;
}
|
Python3
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
|
C#
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;
}
|
Javascript
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++
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];
}
int Floor( int A[], int size, int key)
{
if ( key < A[0] )
return -1;
return Floor(A, 0, size, key);
}
|
C
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];
}
int Floor( int A[], int size, int key)
{
if ( key < A[0] )
return -1;
return Floor(A, 0, size, key);
}
|
Java
public class Floor {
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];
}
static int floor( int [] A, int size, int key)
{
if (key < A[ 0 ])
return - 1 ;
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 ));
}
}
|
Python3
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]
def Floor(A,size,key):
if key<A[ 0 ]:
return - 1
return Floor(A, 0 ,size,key)
|
C#
using System;
public class Floor {
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];
}
static int floor( int [] A, int size, int key)
{
if (key < A[0])
return -1;
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));
}
}
|
Javascript
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];
}
function Floor(A, size, key)
{
if ( key < A[0] )
return -1;
return Floor(A, 0, size, key);
}
|
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>
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;
}
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)
{
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
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;
}
|
C
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;
}
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)
{
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
return (A[left] == key && key == A[right])?
(right - left + 1) : 0;
}
|
Java
public class OccurrencesInSortedArray {
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;
}
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;
}
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));
}
}
|
Python3
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
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):
left = GetLeftPosition(A, - 1 ,size - 1 ,key)
right = GetRightPosition(A, 0 ,size,key)
if A[left] = = key and key = = A[right]:
return right - left + 1
return 0
|
C#
using System;
public class OccurrencesInSortedArray
{
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;
}
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;
}
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));
}
}
|
Javascript
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;
}
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) {
let left = getLeftPosition(A, -1, size - 1, key);
let right = getRightPosition(A, 0, size, key);
if (A[left] === key && key === A[right]) {
return right - left + 1;
}
return 0;
}
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)
{
int m;
if ( A[l] >= A[r] )
return l;
while ( l <= r )
{
if ( l == r )
return l;
m = l + (r-l)/2;
if ( A[m] < A[r] )
r = m;
else
l = m+1;
}
return -1;
}
int BinarySearchIndexOfMinimumRotatedArray( int A[], int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
|
C
int BinarySearchIndexOfMinimumRotatedArray( int A[], int l, int r)
{
int m;
if ( A[l] <= A[r] )
return l;
while ( l <= r )
{
if ( l == r )
return l;
m = l + (r-l)/2;
if ( A[m] < A[r] )
r = m;
else
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)
{
int m;
if (A[l] >= A[r]) {
return l;
}
while (l <= r) {
if (l == r) {
return l;
}
m = l + (r - l) / 2 ;
if (A[m] < A[r]) {
r = m;
} else {
l = m + 1 ;
}
}
return - 1 ;
}
public static int binarySearchIndexOfMinimumRotatedArray( int A[], int size) {
return binarySearchIndexOfMinimumRotatedArray(A, 0 , size - 1 );
}
|
Python3
def BinarySearchIndexOfMinimumRotatedArray(A, l, r):
if A[l] > = A[r]:
return l
while (l < = r):
if l = = r:
return l
m = l + (r - l) / / 2
if A[m] < A[r]:
r = m
else :
l = m + 1
return - 1
def BinarySearchIndexOfMinimumRotatedArray(A, size):
return BinarySearchIndexOfMinimumRotatedArray(A, 0 , size - 1 )
|
C#
using System;
public class Program
{
public static int BinarySearchIndexOfMinimumRotatedArray( int [] A, int l, int r)
{
int m;
if (A[l] >= A[r])
{
return l;
}
while (l <= r)
{
if (l == r)
{
return l;
}
m = l + (r - l) / 2;
if (A[m] < A[r])
{
r = m;
}
else
{
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){
let m;
if (A[l] <= A[r]) return l;
while (l <= r){
if (l == r) return l;
m = l + (r-l)/2;
if (A[m] < A[r]){
r = m;
} else {
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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
28 Oct, 2023
Like Article
Save Article