text: Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void hasArrayTwoPairs ( int nums [ ] , int n , int target ) { sort ( nums , nums + n ) ; 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 ) { cout << nums [ i ] << " , ▁ " ; cout << nums [ mid - 1 ] ; return ; } if ( ( mid + 1 < n ) && nums [ mid + 1 ] == x ) { cout << nums [ i ] << " , ▁ " ; cout << nums [ mid + 1 ] ; return ; } break ; } else { cout << nums [ i ] << " , ▁ " ; cout << nums [ mid ] ; return ; } } } } cout << -1 ; } int main ( ) { int A [ ] = { 0 , -1 , 2 , -3 , 1 } ; int X = -2 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; hasArrayTwoPairs ( A , N , X ) ; return 0 ; }