vb二分法原程序代码

来源:百度知道 编辑:UC知道 时间:2024/06/21 03:45:14

'二分法查找算法(查找失败返回-1,数组下标从0开始)

Public Function BinSearch(ByRef strElement() As String, ByVal strKey As String) As Long
Dim lngLow As Long
Dim lngHigh As Long
Dim lngMiddle As Long
lngLow = 0
lngHigh = UBound(strElement)
While (lngLow <= lngHigh)
lngMiddle = (lngLow + lngHigh) / 2
If strElement(lngMiddle) = strKey Then
BinSearch = lngMiddle
Exit Function
Else
If strElement(lngMiddle) > strKey Then
lngHigh = lngMiddle - 1
Else
lngLow = lngMiddle + 1
End If
End If
Wend
BinSearch = -1 '查找失败
End Function