You are on page 1of 1

Sequences 4/15/2002 11:5

Set Operations
Š We represent a set by the Š Set union:
sorted sequence of its „ aIsLess(a, S)
elements
Sets Š By specializing the auxliliary „
S.insertFirst(a)
bIsLess(b, S)
methods he generic merge S.insertLast(b)
algorithm can be used to „ bothAreEqual(a, b, S)
perform basic set S. insertLast(a)
operations:
„ union
Š Set intersection:
„ aIsLess(a, S)
„ intersection
{ do nothing }
„ subtraction
„ bIsLess(b, S)
Š The running time of an
{ do nothing }
operation on sets A and B
should be at most O(nA + nB) „ bothAreEqual(a, b, S)
S. insertLast(a)

Sets 1 Sets 2

Storing a Set in a List Generic Merging


Š We can implement a set with a list Š Generalized merge Algorithm genericMerge(A, B)
of two sorted lists S ← empty sequence
Š Elements are stored sorted according to some A and B while ¬A.isEmpty() ∧ ¬B.isEmpty()
canonical ordering Š Template method
a ← A.first().element(); b ← B.first().element()
if a < b
Š The space used is O(n) genericMerge aIsLess(a, S); A.remove(A.first())
Š Auxiliary methods else if b < a
Nodes storing set elements in order „ aIsLess bIsLess(b, S); B.remove(B.first())
else { b = a }
„ bIsLess
List ∅ bothAreEqual(a, b, S)
„ bothAreEqual A.remove(A.first()); B.remove(B.first())
Š Runs in O(nA + nB) while ¬A.isEmpty()
time provided the aIsLess(a, S); A.remove(A.first())
auxiliary methods while ¬B.isEmpty()
run in O(1) time bIsLess(b, S); B.remove(B.first())
Set elements return S

Sets 3 Sets 4

Using Generic Merge


for Set Operations

Š Any of the set operations can be


implemented using a generic merge
Š For example:
„ For intersection: only copy elements that
are duplicated in both list
„ For union: copy every element from both
lists except for the duplicates
Š All methods run in linear time.

Sets 5

You might also like