当前位置>>常用算法>>算法9    
返回首页  
 

 
     
 

算法9 折半查找

 
 
算法描述
折半查找法(只能对有序数列进行查找)。
算法分析

 基本思想: 设n个有序数(从小到大)存放在数组a(1)----a(n)中,要查找的数为x。用变量bot、top、mid 分别表示查找数据范围的底部(数组下界)、顶部(数组的上界)和中间,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。

 

代码如下(通过定义一个自定义函数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