Smallest element greater than X not present in the array | Java 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
import java . util . * ; class GFG { static int Next_greater ( int a [ ] , int n , int x ) { Arrays . sort ( a ) ; 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 ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 5 , 10 , 4 , 7 } , x = 4 ; int n = a . length ; System . out . println ( Next_greater ( a , n , x ) ) ; } }