# Randomized Binary Search Algorithm

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.

`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 C++ implementation of Randomized Binary Search

div class="responsive-tabs">

## C++

 `// C++ program to implement recursive ` `// randomized algorithm. ` `#include ` `#include ` `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; ` `} `

## 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 `

Output:

```Element is present at index 3
```

Iterative C++ implementation of Randomized Binary Search

 `// C++ program to implement iterative ` `// randomized algorithm. ` `#include ` `#include ` `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; ` `} `

Output:

```Element is present at index 3
```