Find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and find the other two elements ; To find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element in the remaining elements ; index of the last element ; A [ i ] + A [ l ] + A [ r ] > sum ; If we reach here , then no triplet was found ; Driver program to test above function
def find3Numbers ( A , arr_size , sum ) : NEW_LINE INDENT A . sort ( ) NEW_LINE for i in range ( 0 , arr_size - 2 ) : NEW_LINE INDENT l = i + 1 NEW_LINE r = arr_size - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( A [ i ] + A [ l ] + A [ r ] == sum ) : NEW_LINE INDENT print ( " Triplet ▁ is " , A [ i ] , ' , ▁ ' , A [ l ] , ' , ▁ ' , A [ r ] ) ; NEW_LINE return True NEW_LINE DEDENT elif ( A [ i ] + A [ l ] + A [ r ] < sum ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE sum = 22 NEW_LINE arr_size = len ( A ) NEW_LINE find3Numbers ( A , arr_size , sum ) NEW_LINE