Print all triplets in sorted array that form AP | Function to print all triplets in given sorted array that forms AP ; Search other two elements of AP with arr [ i ] as middle . ; if a triplet is found ; Since elements are distinct , arr [ k ] and arr [ j ] cannot form any more triplets with arr [ i ] ; If middle element is more move to higher side , else move lower side . ; Driver code
< ? php function findAllTriplets ( $ arr , $ n ) { for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) { for ( $ j = $ i - 1 , $ k = $ i + 1 ; $ j >= 0 && $ k < $ n { if ( $ arr [ $ j ] + $ arr [ $ k ] == 2 * $ arr [ $ i ] ) { echo $ arr [ $ j ] . " ▁ " . $ arr [ $ i ] . " ▁ " . $ arr [ $ k ] . " STRNEWLINE " ; $ k ++ ; $ j -- ; } else if ( $ arr [ $ j ] + $ arr [ $ k ] < 2 * $ arr [ $ i ] ) $ k ++ ; else $ j -- ; } } } $ arr = array ( 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 ) ; $ n = count ( $ arr ) ; findAllTriplets ( $ arr , $ n ) ; ? >