Meta Binary Search | One-Sided Binary Search
Last Updated :
21 Feb, 2023
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 Search, is a variation of the binary search algorithm that is used to search an ordered list or array of elements. This algorithm is designed to reduce the number of comparisons needed to search the list for a given element.
The basic idea behind Meta Binary Search is to start with an initial interval of size n that includes the entire array. The algorithm then computes a middle element, as in binary search, and compares it to the target element. If the target element is found, the search terminates. If the middle element is greater than the target element, the algorithm sets the new interval to the left half of the previous interval, and if the middle element is less than the target element, the new interval is set to the right half of the previous interval. However, unlike binary search, Meta Binary Search does not perform a comparison for each iteration of the loop.
Instead, the algorithm uses a heuristic to determine the size of the next interval. It computes the difference between the value of the middle element and the value of the target element, and divides the difference by a predetermined constant, usually 2. This result is then used as the size of the new interval. The algorithm continues until it finds the target element or determines that it is not in the list.
The advantage of Meta Binary Search over binary search is that it can perform fewer comparisons in some cases, particularly when the target element is close to the beginning of the list. The disadvantage is that the algorithm may perform more comparisons than binary search in other cases, particularly when the target element is close to the end of the list. Therefore, Meta Binary Search is most effective when the list is ordered in a way that is consistent with the distribution of the target elements.
Here is the pseudocode for Meta Binary Search:
function meta_binary_search(A, target):
n = length(A)
interval_size = n
while interval_size > 0:
index = min(n - 1, interval_size / 2)
mid = A[index]
if mid == target:
return index
elif mid < target:
interval_size = (n - index) / 2
else:
interval_size = index / 2
return -1
Examples:
Input: [-10, -5, 4, 6, 8, 10, 11], key_to_search = 10
Output: 5
Input: [-2, 10, 100, 250, 32315], key_to_search = -2
Output: 0
The exact implementation varies, but the basic algorithm has two parts:
- Figure out how many bits are necessary to store the largest array index.
- Incrementally construct the index of the target value in the array by determining whether each bit in the index should be set to 1 or 0.
Approach:
- Store number of bits to represent the largest array index in variable lg.
- Use lg to start off the search in a for loop.
- If the element is found return pos.
- Otherwise, incrementally construct an index to reach the target value in the for loop.
- If element found return pos otherwise -1.
Below is the implementation of the above approach:
C++
// C++ implementation of above approach
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
// Function to show the working of Meta binary search
int bsearch(vector<int> A, int key_to_search)
{
int n = (int)A.size();
// Set number of bits to represent largest array index
int lg = log2(n-1)+1;
//while ((1 << lg) < n - 1)
//lg += 1;
int pos = 0;
for (int i = lg ; i >= 0; i--) {
if (A[pos] == key_to_search)
return pos;
// Incrementally construct the
// index of the target value
int new_pos = pos | (1 << i);
// find the element in one
// direction and update position
if ((new_pos < n) && (A[new_pos] <= key_to_search))
pos = new_pos;
}
// if element found return pos otherwise -1
return ((A[pos] == key_to_search) ? pos : -1);
}
// Driver code
int main(void)
{
vector<int> A = { -2, 10, 100, 250, 32315 };
cout << bsearch(A, 10) << endl;
return 0;
}
// This implementation was improved by Tanin
Java
//Java implementation of above approach
import java.util.Vector;
import com.google.common.math.BigIntegerMath;
import java.math.*;
class GFG {
// Function to show the working of Meta binary search
static int bsearch(Vector<Integer> A, int key_to_search) {
int n = (int) A.size();
// Set number of bits to represent largest array index
int lg = BigIntegerMath.log2(BigInteger.valueOf(n-1),RoundingMode.UNNECESSARY) + 1;
//while ((1 << lg) < n - 1) {
// lg += 1;
//}
int pos = 0;
for (int i = lg - 1; i >= 0; i--) {
if (A.get(pos) == key_to_search) {
return pos;
}
// Incrementally construct the
// index of the target value
int new_pos = pos | (1 << i);
// find the element in one
// direction and update position
if ((new_pos < n) && (A.get(new_pos) <= key_to_search)) {
pos = new_pos;
}
}
// if element found return pos otherwise -1
return ((A.get(pos) == key_to_search) ? pos : -1);
}
// Driver code
static public void main(String[] args) {
Vector<Integer> A = new Vector<Integer>();
int[] arr = {-2, 10, 100, 250, 32315};
for (int i = 0; i < arr.length; i++) {
A.add(arr[i]);
}
System.out.println(bsearch(A, 10));
}
}
// This code is contributed by 29AjayKumar
// This implementation was improved by Tanin
Python 3
# Python 3 implementation of
# above approach
# Function to show the working
# of Meta binary search
import math
def bsearch(A, key_to_search):
n = len(A)
# Set number of bits to represent
lg = int(math.log2(n-1)) + 1;
# largest array index
#while ((1 << lg) < n - 1):
#lg += 1
pos = 0
for i in range(lg - 1, -1, -1) :
if (A[pos] == key_to_search):
return pos
# Incrementally construct the
# index of the target value
new_pos = pos | (1 << i)
# find the element in one
# direction and update position
if ((new_pos < n) and
(A[new_pos] <= key_to_search)):
pos = new_pos
# if element found return
# pos otherwise -1
return (pos if(A[pos] == key_to_search) else -1)
# Driver code
if __name__ == "__main__":
A = [ -2, 10, 100, 250, 32315 ]
print( bsearch(A, 10))
# This implementation was improved by Tanin
# This code is contributed
# by ChitraNayal
C#
//C# implementation of above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to show the working of Meta binary search
static int bsearch(List<int> A, int key_to_search)
{
int n = (int) A.Count;
//int lg = 0;
// Set number of bits to represent largest array index
int lg = (int)Math.Log(n-1, 2.0) + 1;
// This is redundant and will cause error
//while ((1 << lg) < n - 1)
//{
// lg += 1;
//}
int pos = 0;
for (int i = lg - 1; i >= 0; i--)
{
if (A[pos] == key_to_search)
{
return pos;
}
// Incrementally construct the
// index of the target value
int new_pos = pos | (1 << i);
// find the element in one
// direction and update position
if ((new_pos < n) && (A[new_pos] <= key_to_search))
{
pos = new_pos;
}
}
// if element found return pos otherwise -1
return ((A[pos] == key_to_search) ? pos : -1);
}
// Driver code
static public void Main()
{
List<int> A = new List<int>();
int[] arr = {-2, 10, 100, 250, 32315};
for (int i = 0; i < arr.Length; i++)
{
A.Add(arr[i]);
}
Console.WriteLine(bsearch(A, 10));
}
}
// This code is contributed by Rajput-Ji
// This implementation was improved by Tanin
PHP
<?php
// PHP implementation of above approach
// Function to show the working of
// Meta binary search
function bsearch($A, $key_to_search, $n)
{
// Set number of bits to represent
$lg = log($n-1, 2) + 1;
// largest array index
// This is redundant and will cause error for some case
//while ((1 << $lg) < $n - 1)
//$lg += 1;
$pos = 0;
for ($i = $lg - 1; $i >= 0; $i--)
{
if ($A[$pos] == $key_to_search)
return $pos;
// Incrementally construct the
// index of the target value
$new_pos = $pos | (1 << $i);
// find the element in one
// direction and update $position
if (($new_pos < $n) &&
($A[$new_pos] <= $key_to_search))
$pos = $new_pos;
}
// if element found return $pos
// otherwise -1
return (($A[$pos] == $key_to_search) ?
$pos : -1);
}
// Driver code
$A = [ -2, 10, 100, 250, 32315 ];
$ans = bsearch($A, 10, 5);
echo $ans;
// This code is contributed by AdeshSingh1
// This implementation was improved by Tanin
?>
JavaScript
<script>
// Javascript implementation of above approach
// Function to show the working of Meta binary search
function bsearch(A, key_to_search)
{
let n = A.length;
// Set number of bits to represent largest array index
let lg = parseInt(Math.log(n-1) / Math.log(2)) + 1;
//while ((1 << lg) < n - 1)
//lg += 1;
let pos = 0;
for (let i = lg ; i >= 0; i--) {
if (A[pos] == key_to_search)
return pos;
// Incrementally construct the
// index of the target value
let new_pos = pos | (1 << i);
// find the element in one
// direction and update position
if ((new_pos < n) && (A[new_pos] <= key_to_search))
pos = new_pos;
}
// if element found return pos otherwise -1
return ((A[pos] == key_to_search) ? pos : -1);
}
// Driver code
let A = [ -2, 10, 100, 250, 32315 ];
document.write(bsearch(A, 10));
</script>
Time Complexity: O(log n), where n is the size of the given array
Auxiliary Space: O(1) , as we are not using any extra space
Reference: https://www.quora.com/What-is-meta-binary-search
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem