Open In App

Meta Binary Search | One-Sided Binary Search

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:  

  1. Figure out how many bits are necessary to store the largest array index.
  2. 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:

  1. Store number of bits to represent the largest array index in variable lg.
  2. Use lg to start off the search in a for loop.
  3. If the element is found return pos.
  4. Otherwise, incrementally construct an index to reach the target value in the for loop.
  5. 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>


Output: 

1

 

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



Previous Article
Next Article

Similar Reads

Number of triangles formed by joining vertices of n-sided polygon with one side common
Given N-sided polygon we need to find the number of triangles formed by joining the vertices of the given polygon with exactly one side being common.Examples: Input : 6 Output : 12 The image below is of a triangle forming inside a Hexagon by joining vertices as shown above. The two triangles formed has one side (AB) common with that of a polygon.It
4 min read
Meta Strings (Check if two strings can become same after a swap in one string)
Given two strings, the task is to check whether these strings are meta strings or not. Meta strings are the strings which can be made equal by exactly one swap in any of the strings. Equal string are not considered here as Meta strings. Examples: Input : str1 = "geeks" str2 = "keegs"Output : YesBy just swapping 'k' and 'g' in any of string, both wi
8 min read
Python 3 | Program to print double sided stair-case pattern
Below mentioned is the Python 3 program to print the double-sided staircase pattern. Examples: Input: 10Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note: This code only works for even values of n. Example1 The given Python code demonstrates a staircase pattern. It d
3 min read
Probability that the pieces of a broken stick form a n sided polygon
We have a stick of length L. The stick got broken at (n-1) randomly chosen points (lengths of parts can be non-integer or floating point numbers also) so we get n parts. We need to find the probability that these n pieces can form a n sided polygon. Examples: Input : L = 5 n = 3 Output : 0.25 We need to cut rope of length 5 into three parts. First
4 min read
Polygon with maximum sides that can be inscribed in an N-sided regular polygon
Given a regular polygon of N sides, the task is to find the maximum sided polygon that can be inscribed inside the given polygon by joining non-adjacent vertices. Print -1, if no such polygon exist. Examples: Input: N = 8Output: 4Explanation:At most a 4 sided polygon can be inscribed inside the given 8-sided polygon as shown below: Input: N = 3Outp
3 min read
Program to find Area of Triangle inscribed in N-sided Regular Polygon
Given the triangle inscribed in an N-sided regular polygon with given side length, formed using any 3 vertices of the polygon, the task is to find the area of this triangle. Examples: Input: N = 6, side = 10 Output: 129.904 Input: N = 8, side = 5 Output: 45.2665 Approach: Consider the 1st example: Given is a 6 sided regular polygon ABCDEF with a tr
6 min read
Side of a regular n-sided polygon circumscribed in a circle
Given two integers r and n where n is the number of sides of a regular polygon and r is the radius of the circle this polygon is circumscribed in. The task is to find the length of the side of polygon. Examples: Input: n = 5, r = 11 Output: 12.9256Input: n = 3, r = 5 Output: 8.6576 Approach: Consider the image above and let angle AOB be theta then
4 min read
Area of a n-sided regular polygon with given side length
Given a regular polygon of N sides with side length a. The task is to find the area of the polygon. Examples: Input : N = 6, a = 9 Output : 210.444 Input : N = 7, a = 8 Output : 232.571 Approach: In the figure above, we see the polygon can be divided into N equal triangles. Looking into one of the triangles, we see that the whole angle at the cente
4 min read
Area of a n-sided regular polygon with given Radius
Given a regular polygon of N sides with radius(distance from the center to any vertex) R. The task is to find the area of the polygon.Examples: Input : r = 9, N = 6 Output : 210.444 Input : r = 8, N = 7 Output : 232.571 In the figure, we see that the polygon can be divided into N equal triangles.Looking into one of the triangles, we see that the wh
4 min read
Length of Diagonal of a n-sided regular polygon
Given a n-sided regular polygon of side length a.The task is to find the length of it's diagonal.Examples: Input: a = 9, n = 10 Output: 17.119 Input: a = 4, n = 5 Output: 6.47213 Approach: We know that the sum of interior angles of a polygon = (n – 2) * 180 where, n is the no. of sides in the polygon. So, each interior angle = (n – 2) * 180/n Now,
4 min read
Article Tags :
Practice Tags :