代码如下(通过定义一个自定义函数search来实现):
Function search(a() As Integer, x As Integer) As Integer
Dim bot%, top%, mid%
Dim find As Boolean '代表是否找到
bot = LBound(a)
top = UBound(a)
find = False '判断是否找到的逻辑变量,初值为False
Do While bot <= top And Not find
mid = (top + bot) \ 2
If x = a(mid) Then
find = True
Exit Do
ElseIf x < a(mid) Then
top = mid - 1
Else
bot = mid + 1
End If
Loop
If find Then
search = mid
Else
search = -1
End If
End Function
|