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:
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
No comments:
Post a Comment