Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Program defines two OrderedListAsArray class methods which search for an object in the ordered list. The IsMember method tests whether a particular object instance is in the ordered list. The Find method locates in the list an object which matches its argument.
Program: OrderedListAsArray class IsMember and Find methods.
The IsMember method is a bool-valued method which takes as its argument a ComparableObject. This method compares the argument one-by-one with the contents of the array. Note that this method tests whether a particular object instance is contained in the ordered list. In the worst case, the object sought is not in the list. In this case, the running time of the method is O(n), where is the number of items in the ordered list.
The Find method also does a search of the ordered list. However, it uses the overloaded == operator to compare the items. Thus, the Find method searches the list for an object which matches its argument. The Find method returns the object found. If no match is found, it returns null. The running time of this method depends on the time required for the comparison operator, . In the worst case, the object sought is not in the list. In this case the running time is . For simplicity, we will assume that the comparison takes a constant amount of time. Hence, the running time of the method is also O(n), where is the number of items in the list.
It is important to understand the subtle distinction between the search done by the IsMember method and that done by Find. The IsMember method searches for a specific object instance while Find simply looks for a matching object. Consider the following:
ComparableInt32 object1 = 57; ComparableInt32 object2 = 57; List list = new OrderedListAsArray(1); list.Insert(object1);This code fragment creates two ComparableInt32 class instances, both of which have the value 57. Only the first object, object1, is inserted into the ordered list list. Consequently, the method call
list.IsMember(object1)returns true; whereas the method call
list.IsMember(object2)returns false.
On the other hand, if a search is done using the Find method like this:
ComparableObject object3 = list.Find(object2);the search will be successful! After the call, object3 and object1 refer to the same object.