Repeatedly search an element by doubling it after every successful search | JavaScript program to repeatedly search an element by doubling it after every successful search ; Sort the given array so that binary search can be applied on it ; Maximum array element ; Search for the element b present or not in array ; Driver code
function binary_search ( a , x , lo = 0 , hi = null ) { if ( hi == null ) hi = a . length ; while ( lo < hi ) { mid = Math . floor ( ( lo + hi ) / 2 ) ; midval = a [ mid ] ; if ( midval < x ) lo = mid + 1 ; else if ( midval > x ) hi = mid ; else return mid ; } return - 1 ; } function findElement ( a , n , b ) { a . sort ( ( a , b ) => a - b ) ; let max = a [ n - 1 ] ; while ( b < max ) { if ( binary_search ( a , a + n , b ) ) b *= 2 ; else return b ; } return b ; } let a = [ 1 , 2 , 3 ] ; let n = a . length ; let b = 1 ; document . write ( findElement ( a , n , b ) ) ;