Notes, algorithm. 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.
An example. 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.
Warning If you use an unsorted List, BinarySearch will give negative indexes that are incorrect.
Info BinarySearch finds the correct indexes. The sorted List contains "cat" at position 0. It contains "mouse" at position 1.
And It contains "zebra" in the final position 2. If you run BinarySearch with an unsorted List, results are invalid.
Dim animals As List(Of String) = New List(Of String)
' This is required!
Dim zebraPosition As Integer = animals.BinarySearch("zebra")
Dim catPosition As Integer = animals.BinarySearch("cat")
Performance. 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.