Given a sorted array and a number x , find the pair in array whose sum is closest to x | A sufficiently large value greater than any element in the input array ; Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver code to test above
MAX_VAL = 1000000000 NEW_LINE def printClosest ( arr , n , x ) : NEW_LINE INDENT res_l , res_r = 0 , 0 NEW_LINE l , r , diff = 0 , n - 1 , MAX_VAL NEW_LINE while r > l : NEW_LINE INDENT if abs ( arr [ l ] + arr [ r ] - x ) < diff : NEW_LINE INDENT res_l = l NEW_LINE res_r = r NEW_LINE diff = abs ( arr [ l ] + arr [ r ] - x ) NEW_LINE DEDENT if arr [ l ] + arr [ r ] > x : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT print ( ' The ▁ closest ▁ pair ▁ is ▁ { } ▁ and ▁ { } ' . format ( arr [ res_l ] , arr [ res_r ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 22 , 28 , 29 , 30 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 54 NEW_LINE printClosest ( arr , n , x ) NEW_LINE DEDENT