Smallest Difference pair of values between two unsorted Arrays | C ++ Code to find Smallest Difference between two Arrays ; function to calculate Small result between two arrays ; Sort both arrays using sort function ; Initialize result as max value ; Scan Both Arrays upto sizeof of the Arrays ; Move Smaller Value ; return final sma result ; Driver Code ; Input given array A ; Input given array B ; Calculate size of Both arrays ; Call function to print smallest result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallestDifference ( int A [ ] , int B [ ] , int m , int n ) { sort ( A , A + m ) ; sort ( B , B + n ) ; int a = 0 , b = 0 ; int result = INT_MAX ; while ( a < m && b < n ) { if ( abs ( A [ a ] - B [ b ] ) < result ) result = abs ( A [ a ] - B [ b ] ) ; if ( A [ a ] < B [ b ] ) a ++ ; else b ++ ; } return result ; } int main ( ) { int A [ ] = { 1 , 2 , 11 , 5 } ; int B [ ] = { 4 , 12 , 19 , 23 , 127 , 235 } ; int m = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int n = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << findSmallestDifference ( A , B , m , n ) ; return 0 ; }