mid=(top+bot)/2,折半查找的算法如下:
(1)x=a(mid),则已找到退出循环,否则进行下面的判断;
(2)x<a(mid),x必定落在bot和mid-1的范围之内,即top=mid-1;
(3)x>a(mid),x必定落在mid+1和top的范围之内,即bot=mid+1;
(4)在确定了新的查找范围后,重复进行以上比较,直到找到或者bot<=top。
将上面的算法写成如下函数,若找到则返回该数所在的下标值,没找到则返回-1。
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