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

Locating Items in an Array-Binary Search

Given a sorted array of items, an efficient way to locate a given item is to use a binary search . The FindOffset member function of the SortedListAsArray class defined in Program gif uses a binary search to locate an item in the array which matches a given item.

   program10756
Program: SortedListAsArray Class FindOffset Member Function Definition

The binary search algorithm makes use of a search interval to determine the position of an item in the sorted list. The search interval is a range of array indices in which the item being sought is expected to be found. The initial search interval is tex2html_wrap_inline61954. The interval is iteratively narrowed by comparing the item sought with the item found in the array at the middle of the search interval. If the middle item matches the item sought, then we are done. Otherwise, if the item sought is less than the middle item, then we can discard the middle item and the right half of the interval; if the item sought is greater than the middle item, we can discard the middle item and the left half of the interval. At each step, the size of the search interval is approximately halved. The algorithm terminates either when the item sough is found, or if the size of the search interval becomes zero.

In the worst case, the item sought is not in the sorted list. Specifically, the worst case occurs when the item sought is smaller than any item in the list because this case requires two comparisons in each iteration of the binary search loop. In the worst case, tex2html_wrap_inline61956 iterations are required. Therefore, the running time of the FindOffset function is tex2html_wrap_inline61958, where tex2html_wrap_inline61960 represents the running time required to compare to Object instances. If we assume that tex2html_wrap_inline61962, then the total running time is simply tex2html_wrap_inline59891, where tex2html_wrap_inline61308.


next up previous contents index

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