Hi all, I'm learning a very useful data struct int C++: set. I know set is a red-black tree so could we join two set into a new set with complexity O(log (number of elements)) in two set? And if we couldn't, what is the best algorithm to join two sets in C++? Thanks for helping.
I dont know is there a way to merge two set
O(log N)
, but if you have N sets and you will merge them one by one until only one set remainder , if u always add all elements from less size set to more size set overall complexity isO(N log^2 N)
. Proof is here , this tree shows worst case because it is balanced :There is about
N log N
nodes at this tree and for each nodethere is average
log N
operations so complexity isO(N log^2 N)
This adds elements of set2 to set1
set1.insert(set2.begin(), set2.end());
Sorry to disappoint, but I'm almost sure that there's no way to do this with STL sets or any other structure. You're basically merging sorted arrays, and the result can vary to any extremes depending on the contents of the arrays.
The best I know is the O(N) (sum of sizes) merging, where you keep 2 iterators looking at the smallest unprocessed element and always take the smaller one.