def bsearch(find, arr, low, high): while low <= high: mid = (low + high) >> 1 if arr[mid] == find: return mid elif arr[mid] > find: high = mid - 1 else: low = mid + 1 return -1 def BaezaYates_intersect_helper(A, B, left1, right1, left2, right2, result): if left1 > right1 or left2 > right2: return if right1-left1 > right2-left2: left1, left2 = left2, left1 right1, right2 = right2, right1 A, B = B, A mid = (left1 + right1) >> 1 index = bsearch(A[mid], B, left2, right2) if index >= 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: if A[mid] > B[right2]: BaezaYates_intersect_helper(A, B, left1, mid-1, left2, right2, result) elif A[mid] < B[left2]: BaezaYates_intersect_helper(A, B, mid+1, right1, left2, right2, result) def BaezaYates_intersect(A, B): result = [] BaezaYates_intersect_helper(A, B, 0, len(A)-1, 0, len(B)-1, result) result.sort() return result from random import randint if __name__ == "__main__": for i in range(2000): A = [randint(0, 100) for i in range(30)] B = [randint(0, 100) for i in range(30)] A.sort() B.sort() #print A #print B inter_set = BaezaYates_intersect(A, B) #print inter_set inter_set2 = set(A) & set(B) for data in inter_set: assert data in inter_set2 print "tests passed..."
时间: 2024-12-29 11:49:46