写了个二分法查找函数

今日有csdn的网友问到这个问题,所以写了这个函数,如下:

'二分法查找函数
'功能:在数组中查找指定的值
'返回:若查到指定值则返回相应的索引,否则返回-1
'程序:by Tang 22:06 2005-4-27
Function vbBinarySearch(vb_Array() As Long, ByVal vb_Find As Long) As Long
    Dim SearchMin As Long
    Dim SearchMax As Long
    Dim i As Long
    vbBinarySearch = -1
    SearchMin = LBound(vb_Array)
    SearchMax = UBound(vb_Array)
    Do
       i = (SearchMax + SearchMin) / 2
       If vb_Array(i) = vb_Find Then
          vbBinarySearch = i
          Exit Do
       End If
       If vb_Array(i) > vb_Find Then
          SearchMax = i - 1
       Else
          SearchMin = i + 1
       End If
    Loop While SearchMax >= SearchMin
End Function

Private Sub Command1_Click()
    Dim vbArr(10) As Integer
    Dim i As Long
    For i = 0 To 10
        vbArr(i) = i + 1
    Next i
    i = vbBinarySearch(vbArr, 7)  '在数组中查找7
    MsgBox i
   
    i = vbBinarySearch(vbArr, 5)  '在数组中查找5
    MsgBox i
   
    i = vbBinarySearch(vbArr, 4)  '在数组中查找4
    MsgBox i

    i = vbBinarySearch(vbArr, 108)  '在数组中查找108
    MsgBox i   'i=-1
End Sub

对应的论坛帖子连接是:

http://community.csdn.net/Expert/topic/3971/3971715.xml?temp=.9264643

'-------------------------------------------
' 转载请注明出处
' 作者:唐细刚
' 邮箱:tanaya@163.com
'-------------------------------------------

阅读更多
个人分类: >> VB6
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭