O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Array.BinarySearch Method

Class

System.Array

Syntax

Array.BinarySearch(array
                  , 
                  value, [comparer]) 
Array.BinarySearch(array, index, length, value, [comparer])
array (required; any array)

The one-dimensional array to be searched

value (required in first overloaded function; any)

The value to search for in array

index (required in second overloaded version; Integer)

The array element at which the search is to start

length (required in second overloaded version; Integer)

The number of array elements to be searched

comparer (optional; IComparer)

A BCL or user-defined class implementing the IComparer interface that determines how two items are compared for equality.

Return Value

An Integer representing the zero-based ordinal position of the element matching value

Description

This method provides a quick way to search for a value in a sorted one-dimensional array, returning the smallest index whose element is that value. It uses a binary search algorithm, which tends to take log2(n) comparisons to find an item in an array of length n. For example, if n = 100,000, the number of comparisons is on the order of 17.

To illustrate, if arr is an array of names in alphabetical order, then the code:

Array.BinarySearch(arr, "steve")

returns the smallest index with element “steve.” If no such element exists, BinarySearch returns the negative number whose bitwise complement is the index of the first element that is larger than “steve.”

Rules at a Glance

  • The array must be a one-dimensional array sorted ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required