Given a sorted and rotated array, find if there is a pair of number with a given sum(method -3)


Question - 

find a pair of element with the given sum in sorted and rotated array.

Example - 

Input : arr[]={5,1,2,3,4} target=5  n=5

Output : 

1 + 4 = 5

2 + 3 = 5


Approach - 

first we find pivot element and pivot element is the largest number in sorted and rotated array which index is end and end+1 is the smallest element of the sorted and rotated array.
Now we calculate the sum of first and last element and 1.  if sum is greater than target then largest element's index decrease by one and if largest element's index is less than 0 then index will be index+size_of_array 2. and if sum is less than target then smallest element's index increases by one and if index will be greater than array of size then index will be (smallest element's index + 1)% size of array.
We do this process until start will not be equal to end.

Implementation - 

#include<iostream>
using namespace std;
void findpair(int arr[],int n,int target)
{
    int i;
    for(i=0;i<n;i++)
        if(arr[i]>arr[i+1])
        break;
    int start=(i+1)%n;
    int end=i;
    while(start!=end){
        
        if(arr[start]+arr[end]==target)
        cout<<arr[start]<<" + "<<arr[end]<<" = "<<target<<endl;
        if(arr[start]+arr[end]>target)
        end=(end+n-1)%n;
        else
        start=(start+1)%n;
        

        
    }
}
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