Search an element in given N ranges | C # implementation of the above 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
using System ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int findNumber ( pair [ ] a , int n , int K ) { int low = 0 , high = n - 1 ; while ( low <= high ) { int 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 ; } public static void Main ( String [ ] args ) { pair [ ] a = { new pair ( 1 , 3 ) , new pair ( 4 , 7 ) , new pair ( 8 , 11 ) } ; int n = a . Length ; int k = 6 ; int index = findNumber ( a , n , k ) ; if ( index != - 1 ) Console . WriteLine ( index ) ; else Console . WriteLine ( - 1 ) ; } }