Examples:
Input:
arr[]= {5, 1, 2, 3, 4}
num = 7
Output: pair Found
Here,
(5,2) sum is 7
Input:
arr[]= {50, 10, 20, 30, 40}
num = 160
Output:
Element is not Found
#include <iostream>
using namespace std;
// Function to find pair that equals sum x
bool findPair(int arr[], int n, int x)
{
// Find the pivot num
int i;
for (i = 0; i < n - 1; i++)
if (arr[i] > arr[i + 1])
break;
// min num
int l = (i + 1) % n;
// max num
int r = i;
while (l != r)
{
if (arr[l] + arr[r] == x)
return true;
// increment or decrement pointers
if (arr[l] + arr[r] < x)
l = (l + 1) % n;
else
r = (n + r - 1) % n;
}
return false;
}
// Main function
int main()
{
int arr[100], N, num;
cout << "Enter Size of array: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
cout << "Enter the num to find pair: ";
cin >> num;
int index = findPair(arr, N, num);
if (index == false)
{
cout << "Pair is not Found";
}
else
{
cout << "Pair is Found";
}
return 0;
}
Output:
Enter Number of nums: 5
5 1 2 3 4
Enter the num to find pair: 5
Pair is Found
0 Comments