text: Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | 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: function hasArrayTwoPairs ( nums , n , target ) { nums . sort ( ) ; var i ; for ( i = 0 ; i < n ; i ++ ) { var x = target - nums [ i ] ; var low = 0 , high = n - 1 ; while ( low <= high ) { var mid = low + ( Math . floor ( ( 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 ) { document . write ( nums [ i ] + " " ) ; document . write ( nums [ mid - 1 ] ) ; return ; } if ( ( mid + 1 < n ) && nums [ mid + 1 ] == x ) { document . write ( nums [ i ] + " " ) ; document . write ( nums [ mid + 1 ] ) ; return ; } break ; } else { document . write ( nums [ i ] + " " ) ; document . write ( nums [ mid ] ) ; return ; } } } } document . write ( - 1 ) ; } var A = [ 0 , - 1 , 2 , - 3 , 1 ] ; var X = - 2 ; var N = A . length ; hasArrayTwoPairs ( A , N , X ) ;