Sets 1 Set Operations We represent a set

  • Slides: 5
Download presentation
Sets 1

Sets 1

Set Operations We represent a set by the sorted sequence of its elements By

Set Operations We represent a set by the sorted sequence of its elements By specializing the auxliliary methods he generic merge algorithm can be used to perform basic set operations: n n n union intersection subtraction Set union: n n n a. Is. Less(a, S) S. insert. First(a) b. Is. Less(b, S) S. insert. Last(b) both. Are. Equal(a, b, S) S. insert. Last(a) Set intersection: n The running time of an operation on sets A and B should be at most O(n. A + n. B) n n Sets a. Is. Less(a, S) { do nothing } b. Is. Less(b, S) { do nothing } both. Are. Equal(a, b, S) S. insert. Last(a) 2

Storing a Set in a List We can implement a set with a list

Storing a Set in a List We can implement a set with a list Elements are stored sorted according to some canonical ordering The space used is O(n) Nodes storing set elements in order List Set elements Sets 3

Generic Merging Generalized merge Algorithm generic. Merge(A, B) S empty sequence of two sorted

Generic Merging Generalized merge Algorithm generic. Merge(A, B) S empty sequence of two sorted lists while A. is. Empty() B. is. Empty() A and B a A. first(). element(); b B. first(). element() Template method if a < b generic. Merge a. Is. Less(a, S); A. remove(A. first()) else if b < a Auxiliary methods n n n a. Is. Less both. Are. Equal Runs in O(n. A + n. B) time provided the auxiliary methods run in O(1) time b. Is. Less(b, S); B. remove(B. first()) else { b = a } both. Are. Equal(a, b, S) A. remove(A. first()); B. remove(B. first()) while A. is. Empty() a. Is. Less(a, S); A. remove(A. first()) while B. is. Empty() b. Is. Less(b, S); B. remove(B. first()) return S Sets 4

Using Generic Merge for Set Operations Any of the set operations can be implemented

Using Generic Merge for Set Operations Any of the set operations can be implemented using a generic merge For example: n n 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