Array.BinarySearch Method |
System.Array
Array.BinarySearch( array , value , [ comparer ] ) Array.BinarySearch( array , index , length , value , [ comparer ])
The one-dimensional array to be searched
The value to search for in array
The array element at which the search is to start
The number of array elements to be searched
A BCL or user -defined class implementing the IComparer interface that determines how two items are compared for equality.
An Integer representing the zero-based ordinal position of the element matching value
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 log 2 (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."
The array must be a one-dimensional array sorted in ascending order.
If value is not found in the array, the method returns a negative number, which is the bitwise complement of the index of the first element that is larger than value . To extract this value, you can use the Not operator, as in the following code fragment:
iResult = Array.BinarySearch(lArr, lSearch) if iResult >= 0 Then MsgBox(iResult) Else MsgBox(iResult & vbcrlf & Not iResult) End If
By default, the System.Collections.Comparer class is used to compare value with the members of array . This means that string comparisons are case sensitive.
If an array contains Boolean values, the method fails to correctly identify the position of the first False value in the array.
In addition to the Comparer class, you can also pass an instance of the System.Collections.CaseInsensitiveComparer class as the comparer argument. It provides for case-insensitive comparisons. For example:
Dim sArr( ) As String = {"Alaska", "ALASKA", "Michigan", "MICHIGAN", _ "New York", "NEW YORK"} Dim sSearch As String Dim lResult As Long Dim oComp As New CaseInsensitiveComparer sSearch = "MICHIGAN" iResult = Array.BinarySearch(sArr, sSearch, oComp)
In this case, because of the case-insensitive comparison, the value of lResult is 2.
Array.IndexOf Method, Array.LastIndexOf Method, Array. Sort Method