BinarySearch
List
BinarySearch
is an optimized search Function. It requires that the List
instance is already sorted. It provides better performance on sorted Lists.
This method hones in on the value by dividing the number of elements being searched several times. It can speed up searches in some real-world programs.
This example program adds 3 Strings to the List
instance. The List
is then sorted with the Sort
Function. It is important to Sort
here.
List
, BinarySearch
will give negative indexes that are incorrect.BinarySearch
finds the correct indexes. The sorted List
contains "cat" at position 0. It contains "mouse" at position 1.BinarySearch
with an unsorted List
, results are invalid.Module Module1 Sub Main() Dim animals As List(Of String) = New List(Of String) animals.Add("zebra") animals.Add("mouse") animals.Add("cat") ' This is required! animals.Sort() Dim zebraPosition As Integer = animals.BinarySearch("zebra") Dim catPosition As Integer = animals.BinarySearch("cat") Console.WriteLine(zebraPosition) Console.WriteLine(catPosition) End Sub End Module2 0
In many programs, it is better to use Dictionary
for lookups. The hashing mechanism in a Dictionary
provides good performance for many real-world programs.
IndexOf
BinarySearch
is faster than IndexOf
on large sorted Lists. But sometimes we know where an element may occur—we can then use IndexOf
to reduce searching time.
IndexOf
will perform better than BinarySearch
.There is an important use case for BinarySearch
. If performance is critical, a hashed lookup is often superior. And if elements are not sorted, IndexOf
is required.