Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate the union and intersection of 2 sets or array 1

Status
Not open for further replies.

jualan

Technical User
Apr 20, 2005
1
US
hello there

i was wondering how do i calculate the union and intesection from 2 arrays of set

lets say set A has { 1,2,3,4,5,0}
and B has { 2,3,4,5,6}

so the union of A and B would be {1,2,2,3,3,4,4,5,5,6,0}
and the intersection would be {2,3,4,5 }


thanksa lot!!
 
1) First sort the arrays in order - 0 should come first.
2) For the union, merge the two sorted arrays
3) For the intersection, try the following
3a)If one value is greater than the other, the lesser one is not in the intersection. Move the next item on the lesser of the two
3b)If they are they are equal, it is in the intersection. Move both to the next item.
3c)Anything remaining once the shorter list has ended is not in the intersection.

If you really want 0 to come last you can stick it at the end after the sets have been obtained. The intersection algo doesn't work if 0 is at the end since 0 < 9.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top