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
def printAllAPTriplets ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT j = i - 1 NEW_LINE k = i + 1 NEW_LINE while ( j >= 0 and k < n ) : NEW_LINE INDENT if ( arr [ j ] + arr [ k ] == 2 * arr [ i ] ) : NEW_LINE INDENT print ( arr [ j ] , " " , arr [ i ] , " " , arr [ k ] ) NEW_LINE k += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ j ] + arr [ k ] < 2 * arr [ i ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 ] NEW_LINE n = len ( arr ) NEW_LINE printAllAPTriplets ( arr , n ) NEW_LINE