find pair of numbers in array that add to given sum

Find pair of numbers in array that add to given sum :

Complexity: O(n logn)

Approach :

step 1: Sort an array using efficient sorting method

step 2: use two variable i & j , initialize i as starting position of array (i=0) and j as last position of array (j=n-1). Where n is number of element in array.

step 3:  if(A[i]+A[j]<x) i++

else if(A[i]+A[j]>x) j–

else (A[i]+A[j]==x) print A[i] , A[j] and  i++

step 4: Repeat step 3 untill i<j

 

Code to Find pair of numbers in array that add to given sum :