Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Finding the Position of an Item and Accessing by Position

Program gif defines two more operations of the OrderedListAsArray class, the FindPosition method and an indexer  this[int]. The FindPosition method takes as its argument a ComparableObject. The purpose of this method is to search the ordered list for an item which matches the object, and to return its position in the form of an object that implements the Cursor interface. In this case, the result is an instance of the private MyCursor class.

   program8924
Program: OrderedListAsArray class FindPosition method and this[int] indexer.

The search algorithm used in FindPosition is identical to that used in the Find method (Program gif). The FindPosition uses the overloaded == operator to locate a contained object which is equal to the search target. Note that if no match is found, the offset is set to the value count, which is one position to the right of the last item in the ordered list. The running time of FindPosition is identical to that of Find: tex2html_wrap_inline60791, where tex2html_wrap_inline60465.

The indexer defined in Program gif provides a get accessor that takes an int argument and returns the object in the ordered list at the specified position. In this case, the position is specified using an integer-valued subscript expression. The implementation of this method is trivial--it simply indexes into the array. Assuming the specified offset is valid, the running time of this method is O(1).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.