Name
Array.BinarySearch Method
Class
System.Array
Syntax
Array.BinarySearch(array, value, [comparer])Array.BinarySearch(array, index, length, value, [comparer])
-
array Use: Required
Data Type: Any array
The one-dimensional array to be searched
-
value Use: Required in first overloaded function
Data Type: Any
The value to search for in
array-
index Use: Required in second overloaded version
Data Type: Integer
The array element at which the search is to start
-
length Use: Required in second overloaded version
Data Type: Integer
The number of array elements to be searched
-
comparer Use: Optional
Data Type:
IComparerA BCL or user-defined class implementing the
IComparerinterface 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access