Option Base 1
Function search(a() As Variant, 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
Private Sub Form_Click()
Dim i As Integer, x() As Variant
Dim y As Integer, k As Integer
x = Array(1, 4, 8, 10, 20, 30, 40, 46, 50, 55, 60, 64)
For i = LBound(x) To UBound(x) '打印输出数组x中的数据
Print x(i);
Next i
Print
y = Val(InputBox("输入要查找的数"))
k = search(x, y) ' 调用查找函数查找数据y
If k = -1 Then
Print "没有找到"; y
Else
Print "找到了,它是第" & k & "个数据"
End If
End Sub