C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
VB.NET program that uses BinarySearch on List
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 Module
Output
2
0
Info: We do not discuss the algorithmic performance of binary search in depth here.
Important: Binary search is rarely needed in real-world programs. But it has an important use case on large sorted Lists.
Tip: If an element comes near the start, IndexOf will perform better than BinarySearch.