Find Union and Intersection of two unsorted arrays | Prints union of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding union , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort the first array and print its elements ( these two steps can be swapped as order in output is not important ) ; Search every element of bigger array in smaller array and print the element if not found ; Prints intersection of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding intersection , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort smaller array arr1 [ 0. . m - 1 ] ; Search every element of bigger array in smaller array and print the element if found ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be presen in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code ; Function call
def printUnion ( arr1 , arr2 , m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT tempp = arr1 NEW_LINE arr1 = arr2 NEW_LINE arr2 = tempp NEW_LINE temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " ▁ " ) NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) == - 1 ) : NEW_LINE INDENT print ( arr2 [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT def printIntersection ( arr1 , arr2 , m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT tempp = arr1 NEW_LINE arr1 = arr2 NEW_LINE arr2 = tempp NEW_LINE temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) != - 1 ) : NEW_LINE INDENT print ( arr2 [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if ( r >= l ) : NEW_LINE INDENT mid = int ( l + ( r - l ) / 2 ) NEW_LINE if ( arr [ mid ] == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ mid ] > x ) : NEW_LINE INDENT return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr1 = [ 7 , 1 , 5 , 2 , 3 , 6 ] NEW_LINE arr2 = [ 3 , 8 , 6 , 20 , 7 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE print ( " Union ▁ of ▁ two ▁ arrays ▁ is ▁ " ) NEW_LINE printUnion ( arr1 , arr2 , m , n ) NEW_LINE print ( " Intersection of two arrays is   " ) NEW_LINE printIntersection ( arr1 , arr2 , m , n ) NEW_LINE