Randomized Binary Search Algorithm | C # program to implement iterative randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A iterative randomized binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int getRandom ( int x , int y ) { return ( int ) ( x + new Random ( 10 ) . Next ( 1 ) * 10 % ( y - x + 1 ) ) ; } static int randomizedBinarySearch ( int [ ] arr , int l , int r , int x ) { while ( l <= r ) { int m = getRandom ( l , r ) ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return - 1 ; } 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 ) ; } }