Question - Given a sorted array, find if there is a pair of number with a given sum(only for sorted array).
Example -
Input : arr[]={1,2,3,4,5} target=5 n=5
Output :
1 + 4 = 5
2 + 3 = 5
method 2 : using single while loop
Approach -
we have a sorted array and we find the pair of number with a given sum. first we calculate the sum of first and last element and if sum is greater than target then last element's index decreases by on and if sum is less than target then first element's index and we do this until sum of pair of number is equal to target or start is less than equal to last.
Implementation -
//find a pair of element with the given sum only in sorted array
#include<iostream>
using namespace std;
void findpair(int arr[],int n,int target)
{
int start=0;
int end=n-1;
while(start<=end){
if(arr[start]+arr[end]==target)
cout<<arr[start]<<" + "<<arr[end]<<" = "<<target<<endl;
if(arr[start]+arr[end]<target)
start++;
else
end--;
}
}
int main()
{
int n;
cout<<"Enter the no of element : ";cin>>n;
int target;
cout<<"Enter target number : ";cin>>target;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
findpair(arr,n,target);
return 0;
}
Comments
Post a Comment