Using a Binary Search Function to Search Numeric Arrays

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

The Filter function works well for searching string arrays, but it is inefficient for numeric arrays. To use the Filter function for a numeric array, you have to convert all of the numeric elements to strings, an extra step that impairs performance. Then you must perform string-comparison operations, when numeric comparisons are much faster.

Although it is more involved, the binary-search algorithm performs efficient searching on a sorted array — whether numeric or string. The binary-search algorithm divides a set of values in half, and determines whether the value being sought lies in the first half or the second half. Whichever half contains the value is kept, and the other half is discarded. The remaining half is then again divided in half, and the process repeats until the algorithm either arrives at the sought value or determines that it is not in the set. Note that the array must be sorted for this algorithm to work.

For an in-depth discussion of the binary-search algorithm, see the Visual Basic Language Developer's Handbook by Ken Getz and Mike Gilbert (Sybex, 2000).

See Also

Understanding Arrays | Creating Arrays | Arrays and Variants | Assigning One Array to Another | Returning an Array from a Function | Passing an Array to a Procedure | Sorting Arrays | Using the Filter Function to Search String Arrays | Searching a Dictionary