Practice
Resources
Contests
Online IDE
New
Free Mock
Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Scaler
Explore Offerings by SCALER

Binary Search

Go to Problems

Level 1

Jump to Level 2

Level 2

Jump to Level 3

Level 3

Jump to Level 4

Level 4

Jump to Level 5

Level 5

Jump to Level 6

Level 6

Jump to Level 7

Level 7

Jump to Level 8

Level 8

Be a Code Ninja!

Binary Search Algorithm

How does Binary Search Work?

Binary search works by repeatedly dividing the array into two halves that can contain the given target element, till the search area is limited to just one element. The necessary condition for binary search to work is the array needs to be sorted

Binary Search Example:

Given a sorted array, find if element 2 is present in the array.

Step 1: The given array:

Step 2: Consider two pointers, low = 0 and high = N - 1, where N is the size of the array.

 

Step 3: Find the mid, i.e. mid = (low + high) / 2. Here, mid = (0 + 6) / 2 = 3.

 Step 4: Now, check for three conditions:

  • Compare if A[mid] = 2
  • Compare if A[mid] > 2
  • Compare if A[mid] < 2
  • It can be observed that, A[mid] = 9, which is > 2, therefore, we shift, high = mid - 1.

Step 5: If A[mid] < 2, shift low = mid + 1.

Step 6: Repeat Steps 3 to Step 5, until the search area is limited to just one element i.e. low = high.

Step 7: The value 2 is found.

Binary Search Implementations

Binary Search can be implemented in mainly two ways:

  • Recursive method
  • Iterative method

Let us first discuss the Recursive method.

Recursive Method


int bSearch(int arr[], int left, int right, int target) {
    if (right >= left) {
        int mid = left + (right - left) / 2;
 
        if (arr[mid] == target)
            return mid;
 
        if (arr[mid] > target)
            return binarySearch(arr, left, mid - 1, target);
 
        return binarySearch(arr, mid + 1, right, target);
    }
    return -1;
}

class BinarySearch {
    int bSearch(int arr[], int left, int right, int target) {
        if (right >= l) {
            int mid = l + (r - l) / 2;
 
            if (arr[mid] == target)
                return mid;
 
            if (arr[mid] > target)
                return binarySearch(arr, left, mid - 1, target);

            return binarySearch(arr, mid + 1, r, x);
       }
       return -1;
   }
}

def bSearch(arr, left, right, target):
    if right >= left:
 
        mid = left + (right - left) // 2

        if arr[mid] == target:
            return mid
 
        elif arr[mid] > target:
            return binarySearch(arr, left, mid-1, target)
 
        else:
            return binarySearch(arr, mid + 1, right, target)
 
    else:
        return -1

Time Complexity :

  • Best Case Complexity : O(logN)
  • Average Case Complexity : O(logN)
  • Worst Case Complexity : O(logN)

Iterative Method


int bSearch(int arr[], int left, int right, int target) {
    while (left <= right) {
        int m = left + (right - left) / 2;
 
        if (arr[m] == target)
            return m;
 
        if (arr[m] < target)
            left = m + 1;
 
        else
            right = m - 1;
    }

    return -1;
}


class BinarySearch {
    int bSearch(int arr[], int left, int right, int target)
    {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int m = left + (right - left) / 2;
 
            if (arr[m] == target)
                return m;
 
            if (arr[m] < target)
                left = m + 1;
 
            else
                right = m - 1;
        }
        return -1;
    }
}

def bSearch(arr, left, right, target):
    while left <= right:
 
        mid = left + (right - left) // 2
 
        if arr[mid] == target:
            return mid
 
        elif arr[mid] < target:
            left = mid + 1
 
        else:
            right = mid - 1
 
    return -1

Time Complexity :

  • Best Case Complexity : O(logN)
  • Average Case Complexity : O(logN)
  • Worst Case Complexity : O(logN)


Walkthrough Examples :

COUNTELEMENTS ROTATEDARRAY

Serious about Learning Programming ?

Learn this and a lot more with Scaler Academy's industry vetted curriculum which covers Data Structures & Algorithms in depth.

Binary Search Problems

Simple binary search
Search answer
Search step simulation
Problem Score Companies Time Status
Implement Power Function 275
59:44
Simple Queries 300
65:03
Sort modification
Problem Score Companies Time Status
Median of Array 325 87:06
Rotated Sorted Array Search 325 56:53
Free Mock Assessment
Fill up the details for personalised experience.
All fields are mandatory
Current Employer *
Enter company name *
Graduation Year *
Select an option *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
*Enter the expected year of graduation if you're student
Current Employer *
Company Name *
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test