Smallest element greater than X not present in the array | C ++ implementation of the approach ; Function to return the smallest element greater than x which is not present in a [ ] ; Sort the array ; Continue until low is less than or equals to high ; Find mid ; If element at mid is less than or equals to searching element ; If mid is equals to searching element ; Increment searching element ; Make high as N - 1 ; Make low as mid + 1 ; Make high as mid - 1 ; Return the next greater element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Next_greater ( int a [ ] , int n , int x ) { sort ( a , a + n ) ; int low = 0 , high = n - 1 , ans = x + 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( a [ mid ] <= ans ) { if ( a [ mid ] == ans ) { ans ++ ; high = n - 1 ; } low = mid + 1 ; } else high = mid - 1 ; } return ans ; } int main ( ) { int a [ ] = { 1 , 5 , 10 , 4 , 7 } , x = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << Next_greater ( a , n , x ) ; return 0 ; }