For two arrays with the following structure:
array = [(index_1, item_1), (index_2, item_2), ..., (index_n, item_n)]
Inside the array, the elements can be un-orderd, for example two Python lists:
arr1 = [(1,'A'), (2, 'B'), (3,'C')]
arr2 = [(3,'c'), (2, 'b'), (1,'a')]
I would like to analyze the merging of these arrays. There are two ways I could think of a merger. The first one is a naive iteration over both arrays:
merged = []
for item in arr:
for item2 in arr2:
if item[0] == item2[0]:
merged.append((item[0], item[1], item2[1]))
This naive approach should be in large o O (n ** 2),
A slightly better (?) Approach was to sort the arrays first (with Python, sort will be O (n log n)):
arr.sort(key=lambda t: t[0])
arr2.sort(key=lambda t: t[0])
for idx, item in enumerate(arrs):
merged_s.append(tuple(list(item)+[arr2s[idx][1]]))
Thus, this approach will be equal to O (n log n) as a whole, is this analysis correct?
What about the case when lists have unequal lengths mand n?
Is there a more efficient way than sorting first?