# Meta Binary Search | One-sided Binary Search

In this article, we are going to see **what is meta binary search and its implementation?** This is a modified version of binary search where we use bit manipulation. It's also known as one-sided Binary Search.

Submitted by Radib Kar, on July 19, 2020

**Meta Binary Search** is a **one-sided binary search** where we work on the index using bit manipulation. We are to find the target index by using bit manipulation like the below example where the algorithm is explained.

Say the input array is *[3, 4, 6, 8, 12, 14, 16]* and searching key says *14*.

The idea is to figure out the target index. And we will do that using bit manipulation and thus we will use the bit representation of the index. On each iteration, we will set the bits.

Now the question is, **how many bits can be there at maximum in the target index?**

Taking the worst case, it's the number of bits in the maximum index (array *len-1*). So for the above example, the maximum number of bits is **3** (max index 6 has 3 bits).

Let's describe the bits as x_{1}x_{2}x_{3}

Now our work is to assign bits from left (MSB) to the right (LSB), 0, or 1 based on the values they should have. Now how would we assign 0 or 1, we will discuss now.

First, we will try to put 1 always, if the current index found has value greater searching key then we will put 0, otherwise it's fine to put 1. If we find the current index found has the same value as the key then we are done.

**So let's start with the example,**

The first bit to be set is the 0^{th} bit, MSB

First set it as 1

So the current index is 1X_{2}X_{3} where X_{2}X_{3} is not either 0, not 1(not set at all). So the minimum current index is right now 100 which is 4(putting 0 in both X_{2}X_{3} which will lead to minimum index). arr[4] is 12 and it's less than the searching key. Thus it's fine to put 1 at X1

Now it's turn for the second bit.

Let's set it with 1 first

So we have 11X_{3}, where X_{3} is not either 0, not 1(not set at all). So the minimum possible current index is right now 110(6). arr[6] is 16 and it's greater than the searching key. Thus we can't set 1st bit as 1. So we need to set that as 0. X_{2} =0

Now it's turn for the 2nd bit(LSB).

Let's set it with 1 first

So we have 101, So the current index is right now 5(101). And, arr[5]=14. We found the searching key and it's at index 5.

This is how Meta Binary Search works. The time complexity is the number of bits to represent the maximum index which is Log(n).

**During the execution of the algorithm**

We found that there can be two types of edge cases:

- We may find any target index while executing which is more than the maximum possible index. Say for example the, length of array is 25. Then, the number of bits we need to represent the maximum index possible->5. So while processing we may need to process any index like 11111 which is more than the maximum index possible. Thus we need to keep a check for this kind of scenario.
- Secondly, the searching key may not even exist, in that case, out of the loop, we will return -1 indicating not found.

## Implementation of the meta binary search algorithm in C++

#include <bits/stdc++.h> using namespace std; int logn(int n) { int count = 0; while (n) { count++; n >>= 1; } return count; } int meta_binary_search(vector<int> arr, int key) { int n = arr.size(); int no_of_bits = logn(n - 1); int cur_index = 0; //iterating log(n) time for (int shift = no_of_bits - 1; shift >= 0; shift--) { //set current bit as 1 int new_cur_index = cur_index + 1 << shift; if (new_cur_index >= n) { //can't set bit as 1 } else { if (arr[new_cur_index] == key) return new_cur_index; //we can set bit as 1 else if (arr[new_cur_index] < key) { cur_index = new_cur_index; } } } //not found return -1; } int main() { vector<int> arr{ 3, 4, 6, 8, 12, 14, 16 }; int key = 12; //key found case int index = meta_binary_search(arr, key); if (index != -1) cout << "key " << key << " found at: " << index << endl; else cout << "key " << key << " not found\n"; //key not found case key = 9; index = meta_binary_search(arr, key); if (index != -1) cout << "key " << key << " found at: " << index << endl; else cout << "key " << key << " not found\n"; return 0; }

**Output:**

key 12 found at: 4 key 9 not found

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Dynamic Programming (Components, Applications and Elements)
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

What's New

- C Language MCQs
- Python MCQs
- Perl MCQs
- MongoDB MCQs
- Java MCQs
- C# MCQs
- Scala MCQs
- Blockchain MCQs
- AutoCAD MCQs
- PHP MCQs
- JavaScript MCQs
- jQuery MCQs
- ReactJS MCQs
- AngularJS MCQs
- JSON MCQs
- Ajax MCQs
- SASS MCQs
- HTML MCQs
- Advanced CSS MCQs
- CSS MCQs
- OOPs MCQs
- PL/SQL MCQs
- SQL MCQs
- Oracle MCQs
- SQLite MCQs
- MS Word MCQs
- Software Engineering MCQs
- Operating System MCQs
- Project Management MCQs
- Data Analytics and Visualization MCQs
- MIS MCQs
- Linux MCQs
- WordPress MCQs
- Blogging MCQs
- Marketing MCQs

- Generally Accepted Accounting Principles MCQs
- Bills of Exchange MCQs
- Business Environment MCQs
- Sustainable Development MCQs
- Marginal Costing and Absorption Costing MCQs
- Globalisation MCQs
- Indian Economy MCQs
- Retained Earnings MCQs
- Depreciation MCQs
- Partnership MCQs
- Sole Proprietorship MCQs
- Goods and Services Tax (GST) MCQs
- Cooperative Society MCQs
- Capital Market MCQs
- Business Studies MCQs
- Basic Accounting MCQs
- MIS Executive Interview Questions
- Go Language Interview Questions

Top Interview Coding Problems/Challenges!

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions!