Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | Java program for the above approach ; Function to check if the array has 2 elements whose sum is equal to the given value ; Sort the array in increasing order ; Traverse the array , nums [ ] ; Store the required number to be found ; Perform binary search ; Store the mid value ; If nums [ mid ] is greater than x , then update high to mid - 1 ; If nums [ mid ] is less than x , then update low to mid + 1 ; Otherwise ; If mid is equal i , check mid - 1 and mid + 1 ; Otherwise , print the pair and return ; If no such pair is found , then print - 1 ; Driver Code ; Function Call
import java . util . * ; class GFG { static void hasArrayTwoPairs ( int nums [ ] , int n , int target ) { Arrays . sort ( nums ) ; for ( int i = 0 ; i < n ; i ++ ) { int x = target - nums [ i ] ; int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = low + ( ( high - low ) / 2 ) ; if ( nums [ mid ] > x ) { high = mid - 1 ; } else if ( nums [ mid ] < x ) { low = mid + 1 ; } else { if ( mid == i ) { if ( ( mid - 1 >= 0 ) && nums [ mid - 1 ] == x ) { System . out . print ( nums [ i ] + " , ▁ " ) ; System . out . print ( nums [ mid - 1 ] ) ; return ; } if ( ( mid + 1 < n ) && nums [ mid + 1 ] == x ) { System . out . print ( nums [ i ] + " , ▁ " ) ; System . out . print ( nums [ mid + 1 ] ) ; return ; } break ; } else { System . out . print ( nums [ i ] + " , ▁ " ) ; System . out . print ( nums [ mid ] ) ; return ; } } } } System . out . print ( - 1 ) ; } public static void main ( String [ ] args ) { int A [ ] = { 0 , - 1 , 2 , - 3 , 1 } ; int X = - 2 ; int N = A . length ; hasArrayTwoPairs ( A , N , X ) ; } }