Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Program defines the constructor for the SetAsArray class as well as the three basic operations--Insert, IsMember, and Withdraw. The constructor takes a single argument , which defines the universe and, consequently, the size of the array of bool values. The constructor creates the empty set by initializing all the elements of the bool array to false. Clearly, the running time of the constructor is O(N).
Program: SetAsArray class constructor, Insert, Withdraw, and IsMember methods.
The Insert method is used to put an item into the set. The method takes an int argument that specifies the item to be inserted. Then the corresponding element of array is set to true to indicate that the item has been added to the set. The running time of the Insert operation is O(1).
The IsMember method is used to test whether a given item is an element of the set. The semantics are somewhat subtle. Since a set does not actually keep track of the specific object instances that are inserted, the membership test is based on the value of the argument. The method simply returns the value of the appropriate element of the array. The running time of the IsMember operation is O(1).
The Withdraw method is used to take an item out of a set. The withdrawal operation is the opposite of insertion. Instead of setting the appropriate array element to true, it is set to false. The running time of the Withdraw is identical to that of Insert, viz., is O(1).