If your sets are sorted, then you can simply iterate through both of them at the same time. If the minimal elements are the same, put that in the intersection and advance the iterator on both sets. If they are not the same, then advance the iterator on the one with the smaller minimal element. You repeat with the rest of the set. This works since the smaller minimal element can't possibly be in the intersection.
In other words, if the sets are {x0, x1, ...} and {y0, y1, ...} in sorted order, the intersection can be defined recursively as:
if (x0 == y0)
then intersection = {x0} + intersection of {x1, x2, ...} and {y1, y2, ...}
else if (x0 < y0)
then intersection = intersection of {x1, x2, ...} and {y0, y1, ...}
else if (x0 > y0)
then intersection = intersection of {x0, x1, ...} and {y1, y2, ...}
Last edited by spooon; 06-01-2006 at 03:10 AM.
|