defbsearch (Find, arr, low, high): whileLow <=High:mid= (low + high) >> 1ifArr[mid] = =Find:returnMidelifArr[mid] >Find:high= Mid-1Else: Low= Mid + 1return-1defBaezayates_intersect_helper (A, B, Left1, right1, left2, right2, result):ifLeft1 > right1orleft2 >right2:return ifRight1-left1 > right2-left2:left1, left2=left2, Left1 right1, right2=right2, right1 A, B=B, A mid= (left1 + right1) >> 1Index=bsearch (A[mid], B, left2, right2)ifIndex >=0:result.append (A[mid]) baezayates_intersect_helper (A, B, LEFT1, mid-1, left2, index-1, result) Baezayates_intersect_helper (A, B, mid+1, right1, index+1, right2, result)Else: ifA[mid] >B[right2]: Baezayates_intersect_helper (A, B, LEFT1, mid-1, left2, right2, result)elifA[mid] <b[left2]: Baezayates_intersect_helper (A, B, mid+1, right1, left2, right2, result)defBaezayates_intersect (A, B): Result=[] Baezayates_intersect_helper (A, B, 0, Len (a)-1, 0, Len (B)-1, result) result.sort ()returnresult fromRandomImportRandintif __name__=="__main__": forIinchRange (2000): A= [Randint (0, 100) forIinchRange (30)] B= [Randint (0, 100) forIinchRange (30)] A.sort () b.sort ()#Print A #Print BInter_set=Baezayates_intersect (A, B)#Print Inter_setInter_set2= Set (A) &Set (B) forDatainchInter_set:assertDatainchInter_set2Print "tests passed ..."
Baezayates intersection Python code