Monday, September 2, 2019

C++: Finding a pair with given sum in an array.

In this programming tutorial, we will read an unsorted array, sort it, and then will find the pair with the given sum.

We maintain a search space in the while loop with 'l' for left index and 'r' for right index. 'l' and 'r' will increment or decrements respectively depending on the sum of the pairs being tested inside the 'while' loop.

Given below is the source code for the algorithm:


#include<iostream>
#include<algorithm>
using namespace std;
void sumPair(int arr[], int n, int sum);
void sumPair(int arr[], int n, int sum) {
std::sort(arr, arr+n);
int l = 0;
int r = n-1;
while( l < r){
if(arr[l]+arr[r] == sum){
cout<<"The pair is "<<arr[l]<<" and "<<arr[r]<<endl;
return;
}
(arr[l]+arr[r] < sum) ? l++: r--;
}
cout<<"The pair with given sum is not found"<<endl;}
int main(){
int arr[] = {5,3,4,6,2,7,1,8,9};
int n = sizeof(arr)/sizeof(arr[0]);
int sum = 10;
sumPair(arr, n, sum);
return 0;
}
view raw find_pair.cpp hosted with ❤ by GitHub

No comments:

Post a Comment