/**There are Given a sorted array.For this we search if there exists any pair of
elements(a[i], a[j]) such that their sum is equal to x. Here We Use Two Pointer Technique.**/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "Enter Array Size :: ";
cin >> n;
int a[n], x;
cout << "\nEnter Array Element :: ";
for(int i=0;i<n;i++) /// Example : {2, 3, 5, 8, 9, 13, 15}
cin >> a[i];
sort(a, a+n); /// For Sort Array Element Ascending Order
cout << "\nEnter Which Element you search :: ";
cin >> x; /// Example : 14
int i = 0, j = n-1; /// Start Two Pointer Technique
int f = 0; /// flag variable for reminder
while(i<j)
{
if(a[i] + a[j] == x)
{
f = 1;
break;
}
else if(a[i] + a[j] < x)
i++;
else
j--;
}
if(f == 0)
cout << x << " Not Found" << "\n";
else
cout << x << " is Found" << "\n";
return 0;
}
Comments
Post a Comment