Minimum difference between adjacent elements of array which contain elements from each row of a matrix | Return smallest element greater than or equal to the current element . ; Return the minimum absolute difference adjacent elements of array ; arr = [ 0 for i in range ( R ) ] [ for j in range ( C ) ] Sort each row of the matrix . ; For each matrix element ; Search smallest element in the next row which is greater than or equal to the current element ; largest element which is smaller than the current element in the next row must be just before smallest element which is greater than or equal to the current element because rows are sorted . ; Driver Program
def bsearch ( low , high , n , arr ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE if ( low <= high ) : NEW_LINE INDENT if ( arr [ mid ] < n ) : NEW_LINE INDENT return bsearch ( mid + 1 , high , n , arr ) ; NEW_LINE DEDENT return bsearch ( low , mid - 1 , n , arr ) ; NEW_LINE DEDENT return low ; NEW_LINE DEDENT def mindiff ( arr , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT sorted ( arr ) NEW_LINE DEDENT ans = 2147483647 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT p = bsearch ( 0 , m - 1 , arr [ i ] [ j ] , arr [ i + 1 ] ) NEW_LINE ans = min ( ans , abs ( arr [ i + 1 ] [ p ] - arr [ i ] [ j ] ) ) NEW_LINE if ( p - 1 >= 0 ) : NEW_LINE INDENT ans = min ( ans , abs ( arr [ i + 1 ] [ p - 1 ] - arr [ i ] [ j ] ) ) NEW_LINE DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT m = [ 8 , 5 ] , [ 6 , 8 ] NEW_LINE print mindiff ( m , 2 , 2 ) NEW_LINE