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