The Wayback Machine - https://web.archive.org/web/20240927192812/https://www.geeksforgeeks.org/randomized-binary-search-algorithm/
Open In App

Randomized Binary Search Algorithm

Last Updated : 25 Jan, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We are given a sorted array A[] of n elements. We need to find if x is present in A or not.In binary search we always used middle element, here we will randomly pick one element in given range.
In Binary Search we had 

middle = (start + end)/2

In Randomized binary search we do following  

Generate a random number t
Since range of number in which we want a random
number is [start, end]
Hence we do, t = t % (end-start+1)
Then, t = start + t;
Hence t is a random number between start and end

It is a Las Vegas randomized algorithm as it always finds the correct result.

Expected Time complexity of Randomized Binary Search Algorithm 
For n elements let say expected time required be T(n), After we choose one random pivot, array size reduces to say k. Since pivot is chosen with equal probability for all possible pivots, hence p = 1/n.
T(n) is sum of time of all possible sizes after choosing pivot multiplied by probability of choosing that pivot plus time take to generate random pivot index.Hence

T(n) = p*T(1) + p*T(2) + ..... + p*T(n) + 1
putting p = 1/n
T(n) = ( T(1) + T(2) + ..... + T(n) ) / n + 1
n*T(n) = T(1) + T(2) + .... + T(n) + n      .... eq(1)
Similarly for n-1
(n-1)*T(n-1) = T(1) + T(2) + ..... + T(n-1) + n-1    .... eq(2)
Subtract eq(1) - eq(2)
n*T(n) - (n-1)*T(n-1) = T(n) + 1
(n-1)*T(n) - (n-1)*T(n-1) =  1
(n-1)*T(n) = (n-1)*T(n-1) + 1
T(n) = 1/(n-1) + T(n-1)
T(n) = 1/(n-1) + 1/(n-2) + T(n-2)
T(n) = 1/(n-1) + 1/(n-2) + 1/(n-3) + T(n-3)
Similarly,
T(n) = 1 + 1/2 + 1/3 + ... + 1/(n-1)
Hence T(n) is equal to (n-1)th Harmonic number, 
n-th harmonic number is O(log n)
Hence T(n) is O(log n) 

Recursive implementation of Randomized Binary Search  

C++




// C++ program to implement recursive
// randomized algorithm.
#include <iostream>
#include <ctime>
using namespace std;
 
// To generate random number
// between x and y ie.. [x, y]
int getRandom(int x, int y)
{
    srand(time(NULL));
    return (x + rand() % (y-x+1));
}
 
// A recursive randomized binary search function.
// It returns location of x in
// given array arr[l..r] is present, otherwise -1
int randomizedBinarySearch(int arr[], int l,
                            int r, int x)
{
    if (r >= l)
    {
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        int mid = getRandom(l, r);
 
        // If the element is present at the
        // middle itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
          return randomizedBinarySearch(arr, l,
                                    mid-1, x);
 
        // Else the element can only be present
        // in right subarray
        return randomizedBinarySearch(arr, mid+1,
                                         r, x);
    }
 
    // We reach here when element is not present
    // in array
    return -1;
}
 
// Driver code
int main(void)
{
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int x = 10;
    int result = randomizedBinarySearch(arr, 0, n-1, x);
    (result == -1)? printf("Element is not present in array")
    : printf("Element is present at index %d", result);
    return 0;
}


Java




// Java program to implement recursive
// randomized algorithm.
public class RandomizedBinarySearch
{
 
    // To generate random number
    // between x and y ie.. [x, y]
    public static int getRandom(int x, int y)
    {
        return (x + (int)(Math.random() % (y-x+1)));
    }
 
    // A recursive randomized binary search function.
    // It returns location of x in
    // given array arr[l..r] is present, otherwise -1
    public static int randomizedBinarySearch(int arr[],
                            int low, int high, int key)
    {
        if (high >= low)
        {
            // Here we have defined middle as
            // random index between l and r ie.. [l, r]
            int mid = getRandom(low, high);
 
            // If the element is present at the
            // middle itself
            if (arr[mid] == key)
                return mid;
 
            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > key)
                return randomizedBinarySearch(arr, low, mid-1, key);
 
            // Else the element can only be present
            // in right subarray
            return randomizedBinarySearch(arr, mid+1, high, key);
        }
 
        // We reach here when element is not present
        // in array
        return -1;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = {2, 3, 4, 10, 40};
        int n = arr.length;
        int key = 10;
        int result = randomizedBinarySearch(arr, 0, n-1, key);
        System.out.println((result == -1)?"Element is not present in array":
                "Element is present at index " + result);
    }
}
 
// This code is contributed by JEREM


Python3




# Python3 program to implement recursive
# randomized algorithm.
# To generate random number
# between x and y ie.. [x, y]
 
import random
def getRandom(x,y):
    tmp=(x + random.randint(0,100000) % (y-x+1))
    return tmp
     
# A recursive randomized binary search function.
# It returns location of x in
# given array arr[l..r] is present, otherwise -1
 
def randomizedBinarySearch(arr,l,r,x) :
    if r>=l:
         
        # Here we have defined middle as
        # random index between l and r ie.. [l, r]
        mid=getRandom(l,r)
         
        # If the element is present at the
        # middle itself
        if arr[mid] == x:
            return mid
             
        # If element is smaller than mid, then
        # it can only be present in left subarray
        if arr[mid]>x:
            return randomizedBinarySearch(arr, l, mid-1, x)
             
        # Else the element can only be present
        # in right subarray
        return randomizedBinarySearch(arr, mid+1,r, x)
         
    # We reach here when element is not present
    # in array
    return -1
     
# Driver code
if __name__=='__main__':
    arr = [2, 3, 4, 10, 40]
    n=len(arr)
    x=10
    result = randomizedBinarySearch(arr, 0, n-1, x)
    if result==-1:
        print('Element is not present in array')
    else:
        print('Element is present at index ', result)
         
# This code is contributes by sahilshelangia


C#




// C# program to implement recursive
// randomized algorithm.
using System;
 
class RandomizedBinarySearch
{
 
    // To generate random number
    // between x and y ie.. [x, y]
    public static int getRandom(int x, int y)
    {
        Random r = new Random();
        return (x + (int)(r.Next() % (y - x + 1)));
    }
 
    // A recursive randomized binary search function.
    // It returns location of x in
    // given array arr[l..r] is present, otherwise -1
    public static int randomizedBinarySearch(int []arr,
                            int low, int high, int key)
    {
        if (high >= low)
        {
            // Here we have defined middle as
            // random index between l and r ie.. [l, r]
            int mid = getRandom(low, high);
 
            // If the element is present at the
            // middle itself
            if (arr[mid] == key)
                return mid;
 
            // If element is smaller than mid, then
            // it can only be present in left subarray
            if (arr[mid] > key)
                return randomizedBinarySearch(arr, low, mid - 1, key);
 
            // Else the element can only be present
            // in right subarray
            return randomizedBinarySearch(arr, mid + 1, high, key);
        }
 
        // We reach here when element is not present
        // in array
        return -1;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = {2, 3, 4, 10, 40};
        int n = arr.Length;
        int key = 10;
        int result = randomizedBinarySearch(arr, 0, n - 1, key);
        Console.WriteLine((result == -1)?"Element is not present in array":
                "Element is present at index " + result);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to implement recursive
 
// To generate random number
// between x and y ie.. [x, y]
function getRandom(x, y) {
    return (x + Math.floor(Math.random() % (y - x + 1)));
}
 
// A recursive randomized binary search function.
// It returns location of x in
// given array arr[l..r] is present, otherwise -1
function randomizedBinarySearch(arr, l, r, x)
{
    if (r >= l)
    {
     
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        let mid = getRandom(l, r);
 
        // If the element is present at the
        // middle itself
        if (arr[mid] == x)
            return mid;
 
        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return randomizedBinarySearch(arr, l,
                mid - 1, x);
 
        // Else the element can only be present
        // in right subarray
        return randomizedBinarySearch(arr, mid + 1,
            r, x);
    }
 
    // We reach here when element is not present
    // in array
    return -1;
}
 
// Driver code
let arr = [2, 3, 4, 10, 40];
let n = arr.length;
let x = 10;
let result = randomizedBinarySearch(arr, 0, n - 1, x);
(result == -1) ? document.write("Element is not present in array")
    : document.write("Element is present at index " + result);
     
    // This code is contributed by saurabh_jaiswal.
</script>


Output: 

Element is present at index 3

Iterative implementation of Randomized Binary Search 

C++




// C++ program to implement iterative
// randomized algorithm.
#include <iostream>
#include <ctime>
using namespace std;
 
// To generate random number
// between x and y ie.. [x, y]
int getRandom(int x, int y)
{
    srand(time(NULL));
    return (x + rand()%(y-x+1));
}
 
// A iterative randomized binary search function.
// It returns location of x in
// given array arr[l..r] if present, otherwise -1
int randomizedBinarySearch(int arr[], int l,
                               int r, int x)
{
    while (l <= r)
    {
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        int m = getRandom(l, r);
 
        // Check if x is present at mid
        if (arr[m] == x)
            return m;
 
        // If x greater, ignore left half
        if (arr[m] < x)
            l = m + 1;
 
        // If x is smaller, ignore right half
        else
            r = m - 1;
    }
 
    // if we reach here, then element was
    // not present
    return -1;
}
 
// Driver code
int main(void)
{
    int arr[] = {2, 3, 4, 10, 40};
    int n = sizeof(arr)/ sizeof(arr[0]);
    int x = 10;
    int result = randomizedBinarySearch(arr, 0, n-1, x);
    (result == -1)? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}


Java




// Java program to implement iterative
// randomized algorithm.
class GFG
{
 
// To generate random number
// between x and y ie.. [x, y]
static int getRandom(int x, int y)
{
     
    return (int) (x + Math.random() * 10 % (y - x + 1));
}
 
// A iterative randomized binary search function.
// It returns location of x in
// given array arr[l..r] if present, otherwise -1
static int randomizedBinarySearch(int arr[], int l,
                                    int r, int x)
{
    while (l <= r)
    {
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        int m = getRandom(l, r);
 
        // Check if x is present at mid
        if (arr[m] == x)
            return m;
 
        // If x greater, ignore left half
        if (arr[m] < x)
            l = m + 1;
 
        // If x is smaller, ignore right half
        else
            r = m - 1;
    }
 
    // if we reach here, then element was
    // not present
    return -1;
}
 
// Driver code
public static void main(String []args)
{
    int arr[] = {2, 3, 4, 10, 40};
    int n = arr.length;
    int x = 10;
    int result = randomizedBinarySearch(arr, 0, n - 1, x);
    if(result == -1)
        System.out.printf("Element is not present in array");
    else
        System.out.printf("Element is present at index %d", result);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python program to implement iterative
# randomized algorithm.
 
# To generate random number
# between x and y ie.. [x, y]
 
from random import randint
 
def getRandom(x, y):
    return randint(x,y)
 
# A iterative randomized binary search function.
# It returns location of x in
# given array arr[l..r] if present, otherwise -1
def randomizedBinarySearch(arr, l, r, x):
    while (l <= r):
        # Here we have defined middle as
        # random index between l and r ie.. [l, r]
        m = getRandom(l, r)
 
        # Check if x is present at mid
        if (arr[m] == x):
            return m
 
        # If x greater, ignore left half
        if (arr[m] < x):
            l = m + 1
 
        # If x is smaller, ignore right half
        else:
            r = m - 1
    # if we reach here, then element was
    # not present
    return -1
 
# Driver code
arr = [2, 3, 4, 10, 40]
n = len(arr)
x = 10
result = randomizedBinarySearch(arr, 0, n-1, x)
if result == 1:
    print("Element is not present in array")
else:
    print("Element is present at index", result)
 
# This code is contributed by ankush_953


C#




// C# program to implement iterative
// randomized algorithm.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// To generate random number
// between x and y ie.. [x, y]
static int getRandom(int x, int y)
{
     
    return (int) (x + new Random(10).Next(1) * 10 % (y - x + 1));
}
 
// A iterative randomized binary search function.
// It returns location of x in
// given array arr[l..r] if present, otherwise -1
static int randomizedBinarySearch(int []arr, int l,
                                    int r, int x)
{
    while (l <= r)
    {
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        int m = getRandom(l, r);
 
        // Check if x is present at mid
        if (arr[m] == x)
            return m;
 
        // If x greater, ignore left half
        if (arr[m] < x)
            l = m + 1;
 
        // If x is smaller, ignore right half
        else
            r = m - 1;
    }
 
    // if we reach here, then element was
    // not present
    return -1;
}
 
// Driver code
public static void Main(String []args)
{
    int []arr = {2, 3, 4, 10, 40};
    int n = arr.Length;
    int x = 10;
    int result = randomizedBinarySearch(arr, 0, n - 1, x);
    if(result == -1)
        Console.Write("Element is not present in array");
    else
        Console.Write("Element is present at index {0}", result);
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program to implement iterative
// randomized algorithm.
 
// To generate random number
// between x and y ie.. [x, y]
function getRandom(x,y)
{
     return Math.floor(x + Math.floor(Math.random() * 10) %
                      (y - x + 1));
}
 
// A iterative randomized binary search function.
// It returns location of x in
// given array arr[l..r] if present, otherwise -1
function randomizedBinarySearch(arr,l,r,x)
{
    while (l <= r)
    {
         
        // Here we have defined middle as
        // random index between l and r ie.. [l, r]
        let m = getRandom(l, r);
   
        // Check if x is present at mid
        if (arr[m] == x)
            return m;
   
        // If x greater, ignore left half
        if (arr[m] < x)
            l = m + 1;
   
        // If x is smaller, ignore right half
        else
            r = m - 1;
    }
   
    // If we reach here, then element was
    // not present
    return -1;
}
 
// Driver code
let arr = [ 2, 3, 4, 10, 40 ];
let n = arr.length;
let x = 10;
let result = randomizedBinarySearch(arr, 0, n - 1, x);
 
if (result == -1)
    document.write("Element is not present in array");
else
    document.write("Element is present at index ",
                   result);
 
// This code is contributed by rag2127
 
</script>


Output: 

Element is present at index 3

 



Previous Article
Next Article

Similar Reads

Count of array elements that can be found using Randomized Binary Search on every array element
Given an array arr[] of size N, the task is to find the minimum count of array elements found by applying the Randomized Binary Search for each array elements. Examples: Input: arr[] = { 5, 4, 9 } Output: 2 Explanation: Applying Randomized Binary Search for arr[0] in the array. Initially, search space is [0, 2] Suppose pivot = 1 and arr[pivot] <
7 min read
Treap (A Randomized Binary Search Tree)
Like Red-Black and AVL Trees, Treap is a Balanced Binary Search Tree, but not guaranteed to have height as O(Log n). The idea is to use Randomization and Binary Heap property to maintain balance with high probability. The expected time complexity of search, insert and delete is O(Log n). Every node of Treap maintains two values. 1) Key Follows stan
2 min read
Load Balancing on Servers (Randomized Algorithm)
Consider a high traffic website that receives millions of requests (of different types) per five minutes, the site has k (for example n = 1000) servers to process the requests. How should the load be balanced among servers? The solutions that we generally think of are a) Round Robin b) Assign new request to a server that has minimum load. Both of t
3 min read
Randomized Algorithm in Python
Randomized algorithms are algorithms that use randomness as part of their logic to achieve efficiency and simplicity in solving computational problems. Unlike deterministic algorithms, which produce the same output for a given input, randomized algorithms may produce different outputs for the same input due to the involvement of randomness. These a
7 min read
Disjoint Set Union (Randomized Algorithm)
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find. The disjoint set union algorithm allows you to perform the following operations efficiently: Find: Determine which set a given element belongs to.
15+ min read
Importance of Randomized Algorithms
Introduction: Randomization is an important concept, and hence randomization algorithms are used in a variety of fields, such as number theory, computational geometry, graph theory, and distributed computing.The inputs for a randomized algorithm are similar to those of deterministic algorithms, along with a sequence of random bits that can be used
4 min read
Randomized Algorithms | Set 1 (Introduction and Analysis)
What is a Randomized Algorithm? An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger's algorithm, we randomly pick an edge. How to analyse Randomize
6 min read
Randomized Algorithms | Set 2 (Classification and Applications)
We strongly recommend to refer below post as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Classification Randomized algorithms are classified in two categories. Las Vegas: A Las Vegas algorithm were introduced by Laszlo Babai in 1979. A Las Vegas algorithm is an algorithm which uses randomness, but gives guarant
13 min read
Randomized Algorithms | Set 3 (1/2 Approximate Median)
We strongly recommend to refer below articles as a prerequisite of this. Randomized Algorithms | Set 1 (Introduction and Analysis) Randomized Algorithms | Set 2 (Classification and Applications) In this post, a Monte Carlo algorithm is discussed. Problem Statement : Given an unsorted array A[] of n numbers and ε > 0, compute an element w
4 min read
Randomized Algorithms | Set 0 (Mathematical Background)
Conditional Probability Conditional probability P(A | B) indicates the probability of even 'A' happening given that the even B happened.[Tex]P(A|B) = \frac{P(A\cap B)}{P(B)} [/Tex]We can easily understand above formula using below diagram. Since B has already happened, the sample space reduces to B. So the probability of A happening becomes P(A ? B
3 min read
Randomized Algorithms
Randomized algorithms in data structures and algorithms (DSA) are algorithms that use randomness in their computations to achieve a desired outcome. These algorithms introduce randomness to improve efficiency or simplify the algorithm design. By incorporating random choices into their processes, randomized algorithms can often provide faster soluti
2 min read
Meta Binary Search | One-Sided Binary Search
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 Searc
9 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Search N elements in an unbalanced Binary Search Tree in O(N * logM) time
Given an Unbalanced binary search tree (BST) of M nodes. The task is to find the N elements in the Unbalanced Binary Search Tree in O(N*logM) time. Examples: Input: search[] = {6, 2, 7, 5, 4, 1, 3}. Consider the below tree Output:FoundNot FoundFoundFoundFoundFoundNot Found Naive Approach: For each element, we will try to search for that element in
8 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Interpolation search vs Binary search
Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key. If the value of the search-key is close to the last element, Interpolation Sea
7 min read
Linear Search vs Binary Search
Prerequisite: Linear SearchBinary SearchLINEAR SEARCH Assume that item is in an array in random order and we have to find an item. Then the only way to search for a target item is, to begin with, the first position and compare it to the target. If the item is at the same, we will return the position of the current item. Otherwise, we will move to t
11 min read
Why is Binary Search preferred over Ternary Search?
The following is a simple recursive Binary Search function in C++ taken from here. C/C++ Code // CPP program for the above approach #include <bits/stdc++.h> using namespace std; // A recursive binary search function. It returns location of x in // given array arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x)
11 min read
What is the difference between Binary Search and Jump Search?
Binary Search and Jump Search are two popular algorithms used for searching elements in a sorted array. Although they both try to identify a target value as quickly as possible, they use distinct approaches to get there. In this article, we will discuss the difference between binary search and jump search. Let's explore how these algorithms optimiz
2 min read
Is ternary search faster than binary search?
Binary search is a widely used algorithm for searching a sorted array. It works by repeatedly dividing the search space in half until the target element is found. Ternary search is a variation of binary search that divides the search space into three parts instead of two. This article explores the performance comparison between ternary search and b
3 min read
Which is faster between binary search and linear search?
In computer science, search algorithms are used to locate a specific element within a data structure. Two commonly used search algorithms are binary search and linear search. Understanding their relative speeds is crucial for optimizing search operations. Let's compare the speed of Binary Search and Linear Search to determine which one is faster. B
2 min read
Is there any search faster than Binary Search?
No, there is no search faster than Binary Search. Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc. How Does Binary Search Work?Bin
3 min read
Is exponential search faster than binary search?
Exponential search and binary search are two algorithms used to find a target element in a sorted array. While both algorithms have their advantages and disadvantages, exponential search is generally not considered to be faster than binary search. Time Complexity of Exponential Search:The time complexity of exponential search is O(log n), where n i
2 min read
What is Binary Search Algorithm?
Binary Search is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half and the correct interval to find is decided based on the searched value and the mid value of the interval. Properties of Binary Search:Binary search is performed on the sorted data structure for example sorted array. Searching is done by
1 min read
Rearrange Array to find K using Binary Search algorithm without sorting
Given an array, arr[] of N distinct integers and an integer K, the task is to rearrange the given array in such a way, that K can be found with the help of Binary Search Algorithm in the rearranged array. Please note, the array is not to be sorted. Examples: Input: arr[] = {10, 7, 2, 5, 3, 8}, K = 7Output: 3 7 8 5 2 10 Explanation: Finding K in out
14 min read
Bitwise Binary Search algorithm
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: 76 = 64 + 8 + 410 = 8 + 27 = 4 + 2 + 1 Approach: Compute the first power of 2 that is greater or equal then the size of the array.Initializ
7 min read
N-Base modified Binary Search algorithm
N-Base modified Binary Search is an algorithm based on number bases that can be used to find an element in a sorted array arr[]. This algorithm is an extension of Bitwise binary search and has a similar running time. Examples: Input: arr[] = {1, 4, 5, 8, 11, 15, 21, 45, 70, 100}, target = 45Output: 7Explanation: The value 45 is present at index 7 I
10 min read
Day-Stout-Warren algorithm to balance given Binary Search Tree
Given an unbalanced Binary Search Tree (BST), the task is to convert it into a balanced BST in linear time and without using auxiliary space. Examples: Input: 5 / \ 1 10 \ 20 \ 35Output: 20 / \ 5 35 / \ 1 10 Input: 10 / 5 / 2 / 1Output: 5 / \ 2 10 / 1 Approach: The algorithm used in this scenario is the Day-Stout-Warren algorithm. The balanced tree
14 min read
Time and Space Complexity Analysis of Binary Search Algorithm
Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space. AspectComplexityTime ComplexityO(log n)Space ComplexityO(1)The time and space complexities of the binary search algorithm are mentioned below.
3 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read