Search an element in given N ranges | JavaScript implementation of the approach ; Function to return the index of the range in which K lies and uses binary search ; Binary search ; Find the mid element ; If element is found ; Check in first half ; Check in second half ; Not found ; Driver code
class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } function findNumber ( a , n , K ) { var low = 0 , high = n - 1 ; while ( low <= high ) { var mid = ( low + high ) >> 1 ; if ( K >= a [ mid ] . first && K <= a [ mid ] . second ) return mid ; else if ( K < a [ mid ] . first ) high = mid - 1 ; else low = mid + 1 ; } return - 1 ; } var a = [ new pair ( 1 , 3 ) , new pair ( 4 , 7 ) , new pair ( 8 , 11 ) ] ; var n = a . length ; var k = 6 ; var index = findNumber ( a , n , k ) ; if ( index != - 1 ) document . write ( index ) ; else document . write ( - 1 ) ;