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

Linear Search

Program gif gives the naıve version of the find method of the MWayTree class. The find method takes a Comparable object and locates the item in the search tree which matches the given object.

   program20732
Program: MWayTree class find method (linear search).

Consider the execution of the find method for a node T of a an M-way search tree. Suppose the object of the search is x. Clearly, the search fails when tex2html_wrap_inline62506 (lines 10-11). In this case, null is returned.

Suppose tex2html_wrap_inline64318. The linear search on lines 13-20 considers the keys tex2html_wrap_inline63246, tex2html_wrap_inline64322, tex2html_wrap_inline64324, ..., tex2html_wrap_inline63242, in that order. If a match is found, the matching object is returned immediately (lines 16-17).

Otherwise, when the main loop terminates there are three possibilities: i=0 and tex2html_wrap_inline64330; tex2html_wrap_inline64332 and tex2html_wrap_inline63322; or i=n-1 and tex2html_wrap_inline64338. In all three cases, the appropriate subtree in which to continue search is tex2html_wrap_inline62338 (line 21).

Clearly the running time of Program gif is determined by the main loop. In the worst case, the loop is executed M-1 times. Therefore, at each node in the search path at most M-1 object comparisons are done.

Consider an unsuccessful search in an M-way search tree. The running time of the find method is

displaymath64308

in the worst case, where h is the height of the tree and tex2html_wrap_inline63654 is the time required to compare two objects. Clearly, the time for a successful search has the same asymptotic bound. If the tree is balanced and tex2html_wrap_inline63662, then the running time of Program gif is tex2html_wrap_inline64354, where K is the number of keys in the tree.


next up previous contents index

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