Open In App

Bitwise Binary Search algorithm

Last Updated : 17 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisite: Binary Search

Bitwise Binary Search algorithm is a modified version of Binary Search based on the following idea:

Every number can be represented as a sum of the powers of the number 2.

Examples:

  1. 76 = 64 + 8 + 4
  2. 10 = 8  + 2
  3. 7 = 4 + 2 + 1
 

Approach:

  • Compute the first power of 2 that is greater or equal then the size of the array.
  • Initialize an index as 0.
  • Loop while the computed power is greater than 0 and each time divide it by 2.
  • Each time the element at position [index + power] <= target we add to the index variable the respective power value. (Build the sum)
  • After the for loops check if the element at position [index] == target. If so the target element is present in the array, else not.
  • (no division needed only addition and bitwise shifting)

C++

// C++ program to implement Bitwise Binary Search
  
#include <iostream>
  
using namespace std;
  
int binary_search(int* arr, int size, int target)
{
    int index, power;
  
    // Compute the first power of 2 that is >= size
    for (power = 1; power < size; power <<= 1)
        ;
  
    // loop while(power > 0)
    // and divide power by two each iteration
    for (index = 0; power; power >>= 1) {
  
        // if the next condition is true
        // it means that the power value can contribute to
        // the "sum"(a closer index where target might be)
        if (index + power < size
            && arr[index + power] <= target)
            index += power;
    }
  
    // if the element at position [index] == target,
    // the target value is present in the array
    if (arr[index] == target)
        return index;
  
    // else the value is not present in the array
    return -1;
}
  
int main()
{
    int arr[5] = { 1, 3, 5, 7, 8 };
    int size = 5;
    int x = 3;
    int answer = binary_search(arr, size, x);
    if (answer == -1)
        cout << "Element not found";
    else
        cout << "Element found at position " << answer;
 // This code is contributed
 // by Gatea David
}

                    

Java

// Java program to implement Bitwise Binary Search
import java.util.*;
  
class GFG {
  
    static int binary_search(int[] arr, int size,
                             int target)
    {
        int index, power;
  
        // Compute the first power of 2 that is >= size
        for (power = 1; power < size; power <<= 1)
            ;
  
        // loop while(power > 0)
        // and divide power by two each iteration
        for (index = 0; power > 0; power >>= 1) {
  
            // if the next condition is true
            // it means that the power value can
            // contribute to the "sum"(a closer index where
            // target might be)
            if (index + power < size
                && arr[index + power] <= target)
                index += power;
        }
  
        // if the element at position [index] == target,
        // the target value is present in the array
        if (arr[index] == target)
            return index;
  
        // else the value is not present in the array
        return -1;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 1, 3, 5, 7, 8 };
        int size = 5;
        int x = 3;
        int answer = binary_search(arr, size, x);
        if (answer == -1)
            System.out.print("Element not found");
        else
            System.out.print("Element found at position "
                             + answer);
    }
}

                    

Python3

# Python code for the above approach
def binary_search(arr, size, target):
  
    # Compute the first power of 2 that is >= size
    power = 1
    while(power < size):
        power = power << 1
          
    # loop while(power > 0)
    # and divide power by two each iteration
    power = 1
    index = 0
    while(power):
  
        # if the next condition is true
        # it means that the power value can contribute to
        # the "sum"(a closer index where target might be)
        if (index + power < size and arr[index + power] <= target):
            index += power
        power >>= 1
  
    # if the element at position [index] == target,
    # the target value is present in the array
    if (arr[index] == target):
        return index
  
    # else the value is not present in the array
    return -1
  
arr = [1, 3, 5, 7, 8]
size = 5
x = 3
answer = binary_search(arr, size, x)
if (answer == -1):
    print("Element not found")
else:
    print(f"Element found at position {answer}")
  
# This code is contributed by gfgking

                    

C#

// C# program to implement Bitwise Binary Search
using System;
class GFG {
    static int binary_search(int[] arr, int size,
                             int target)
    {
        int index, power;
  
        // Compute the first power of 2 that is >= size
        for (power = 1; power < size; power <<= 1)
            ;
  
        // loop while(power > 0)
        // and divide power by two each iteration
        for (index = 0; power != 0; power >>= 1) {
  
            // if the next condition is true
            // it means that the power value can contribute
            // to the "sum"(a closer index where target
            // might be)
            if (index + power < size
                && arr[index + power] <= target)
                index += power;
        }
  
        // if the element at position [index] == target,
        // the target value is present in the array
        if (arr[index] == target)
            return index;
  
        // else the value is not present in the array
        return -1;
    }
  
    public static int Main()
    {
        int[] arr = new int[] { 1, 3, 5, 7, 8 };
        int size = 5;
        int x = 3;
        int answer = binary_search(arr, size, x);
        if (answer == -1)
            Console.Write("Element not found");
        else
            Console.Write("Element found at position "
                          + answer);
        return 0;
    }
}
  
// This code is contributed by Taranpreet

                    

Javascript

<script>
       // JavaScript code for the above approach
       function binary_search(arr, size, target)
       {
           let index, power;
 
           // Compute the first power of 2 that is >= size
           for (power = 1; power < size; power <<= 1)
               ;
 
           // loop while(power > 0)
           // and divide power by two each iteration
           for (index = 0; power; power >>= 1) {
 
               // if the next condition is true
               // it means that the power value can contribute to
               // the "sum"(a closer index where target might be)
               if (index + power < size
                   && arr[index + power] <= target)
                   index += power;
           }
 
           // if the element at position [index] == target,
           // the target value is present in the array
           if (arr[index] == target)
               return index;
 
           // else the value is not present in the array
           return -1;
       }
 
       let arr = [1, 3, 5, 7, 8];
       let size = 5;
       let x = 3;
       let answer = binary_search(arr, size, x);
       if (answer == -1)
           document.write("Element not found");
       else
           document.write("Element found at position " + answer);
 
      // This code is contributed by Potta Lokesh
   </script>

                    

 
 


Output
Element found at position 1


 

Time Complexity: Theta(Logn)


 

The time complexity of Binary Search can be written as:


 

T(n) = T(n/2) + c


 

The above recurrence can be solved either using the Recurrence Tree method or the Master method. It falls in case II of the Master Method and the solution of the recurrence is Theta(Logn)


 

Auxiliary Space: O(1) in case of iterative implementation. In the case of recursive implementation, O(Logn) recursion call stack space.


 

Algorithmic Paradigm: Decrease and Conquer.


 

Note:


 

Here we are using 


 

int mid = low + (high – low)/2;


 

Maybe, you wonder why we are calculating the middle index this way, we can simply add the lower and higher index and divide it by 2.


 

int mid = (low + high)/2;


 

But if we calculate the middle index like this means our code is not 100% correct, it contains bugs.


 

That is, it fails for larger values of int variables low and high. Specifically, it fails if the sum of low and high is greater than the maximum positive int value(231 – 1 ).


 

The sum overflows to a negative value and the value stays negative when divided by 2. In java, it throws ArrayIndexOutOfBoundException.


 

int mid = low + (high – low)/2;


 

So it’s better to use it like this. This bug applies equally to merge sort and other divide and conquer algorithms.


 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads