VB.NET - Implimentation of Binary Search.
Posted: Mon Aug 02, 2004 3:46 pm
Code: Select all
Option Explicit On
Module Main
Public Sub Main()
Dim ssource(5) As String
ssource(0) = "alpha"
ssource(1) = "beta"
ssource(2) = "cow"
ssource(3) = "monster"
ssource(4) = "monsters go"
ssource(5) = "zzzz"
Debug.WriteLine(search(ssource, "monsters go"))
End Sub
Public Function search(ByVal ssource() As String, ByVal starget As String) As Long
Dim lhigh As Long = UBound(ssource)
Dim llow As Long = -1
Dim lprobe As Long
While (lhigh - llow > 1)
lprobe = (lhigh + llow) \ 2
If (ssource(lprobe) < starget) Then
llow = lprobe
Else
lhigh = lprobe
End If
End While
If (lhigh = UBound(ssource) Or ssource(lhigh) <> starget) Then
Return -1
Else
Return lhigh
End If
End Function
Public Function search(ByVal lsource() As Long, ByVal ltarget As Long) As Long
Dim lhigh As Long = UBound(lsource)
Dim llow As Long = -1
Dim lprobe As Long
While (lhigh - llow > 1)
lprobe = (lhigh + llow) \ 2
If (lsource(lprobe) < ltarget) Then
llow = lprobe
Else
lhigh = lprobe
End If
End While
If (lhigh = UBound(lsource) Or lsource(lhigh) <> ltarget) Then
Return -1
Else
Return lhigh
End If
End Function
End Module