Search an element in given N ranges | C ++ implementation of the approach ; Function to return the index of the range in which K lies and uses linear search ; Iterate and find the element ; If K lies in the current range ; K doesn 't lie in any of the given ranges ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( pair < int , int > a [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( K >= a [ i ] . first && K <= a [ i ] . second ) return i ; } return -1 ; } int main ( ) { pair < int , int > a [ ] = { { 1 , 3 } , { 4 , 7 } , { 8 , 11 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 6 ; int index = findNumber ( a , n , k ) ; if ( index != -1 ) cout << index ; else cout << -1 ; return 0 ; }