Given a sorted and rotated array , find if there is a pair with a given sum | C ++ program to find number of pairs with a given sum in a sorted and rotated array . ; This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of number of pairs . ; Find sum of pair formed by arr [ l ] and and arr [ r ] and update l , r and cnt accordingly . ; If we find a pair with sum x , then increment cnt , move l and r to next element . ; This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; If current pair sum is less , move to the higher sum side . ; If current pair sum is greater , move to the lower sum side . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pairsInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; int cnt = 0 ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) { cnt ++ ; if ( l == ( r - 1 + n ) % n ) { return cnt ; } l = ( l + 1 ) % n ; r = ( r - 1 + n ) % n ; } else if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return cnt ; } int main ( ) { int arr [ ] = { 11 , 15 , 6 , 7 , 9 , 10 } ; int sum = 16 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << pairsInSortedRotated ( arr , n , sum ) ; return 0 ; }