Given a sorted and rotated array , find if there is a pair with a given sum | 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 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 Code
< ? php function pairsInSortedRotated ( $ arr , $ n , $ x ) { $ i ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) if ( $ arr [ $ i ] > $ arr [ $ i + 1 ] ) break ; $ l = ( $ i + 1 ) % $ n ; $ r = $ i ; $ 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 ; } $ arr = array ( 11 , 15 , 6 , 7 , 9 , 10 ) ; $ sum = 16 ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo pairsInSortedRotated ( $ arr , $ n , $ sum ) ; ? >