Open In App

The Ubiquitous Binary Search | Set 1

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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] &lt;= key and A[r] &gt; 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] &lt;= key and A[r] &gt; 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] &lt;= key and A[r] &gt; 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.



Previous Article
Next Article

Similar Reads

Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta Binary Search, also known as One-Sided Binary Searc
9 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
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/C++ Code // CPP program for the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Article Tags :
Practice Tags :