编写一个函数,实现两分法查找算法。
题目:
编写一个函数,实现两分法查找算法。
两分法查找的思想是,首先假设在查找的数字数组中,是按照从小到大的顺序排列的,要查找的关键值首先同中间的元素比较,若相同则查找成功,否则根据这个中间的数与要查找的数的大小关系,保留一半,在数组的另外一半中进行查找,如此重复,每次都到中音的数据去进行比较,每次将减少一半的查找的数据,因此效率比较高。
编写的程序在数组ABC(1,2,3,4,5,6,7,8,9,10)中查找到其中任何数字.
提示:采用一个递归的算法来实现.
只用两分法已搞定,代码如下:
Dim times As Long
Dim vbarr() As Long

Private Sub Command1_Click()
    ReDim vbarr(Val(Text1.Text)) As Long
    Dim i As Long
    For i = 0 To Val(Text1.Text)
        vbarr(i) = i + 1
    Next i
        i = search(vbarr, Text2.Text)
    Text3.Text = "找到数字" & i & "共查找了" & times & "次"
  
End Sub
Public Function search(vbArray() As Long, ByVal vb_find As Long) As Long
Dim searchmin As Long
Dim searchmax As Long
Dim i As Long
searchmin = LBound(vbArray)
searchmax = UBound(vbArray)
Do
i = (searchmax + searchmin) / 2
times = times + 1
If vb_find = vbArray(i) Then
    search = vbArray(i)
    Exit Do
End If
If vb_find > vbArray(i) Then
    searchmin = i + 1
Else
    searchmax = i - 1
End If
Loop While searchmax >= searchmin
End Function
用递归法来实现,
Dim times As Long
Dim vbarr() As Long
Dim find As Long

Private Sub Command1_Click()
    ReDim vbarr(Val(Text1.Text)) As Long
    Dim i As Long
    For i = 0 To Val(Text1.Text)
        vbarr(i) = i + 1
    Next i
        search vbarr, Text2.Text, CLng(0), CLng(Text1.Text)
    Text3.Text = "找到数字" & find & "共查找了" & times & "次"
   
End Sub
Public Function search(vbArray() As Long, ByVal vb_find As Long, nStr As Long, nEnd As Long) As Long
Dim searchmin As Long
Dim searchmax As Long

searchmin = nStr
searchmax = nEnd

i = (searchmax + searchmin) / 2
times = times + 1

If i >= UBound(vbArray) Or i <= LBound(vbArray) Then Exit Function

If vb_find = vbArray(i) Then
    find = vbArray(i)
Else

If vb_find > vbArray(i) Then
    
    searchmin = i + 1
Else
     searchmax = i - 1
End If
search vbarr, Text2.Text, searchmin, searchmax
End If
End Function
阅读更多
个人分类: QB/VB
想对作者说点什么? 我来说一句

分块查找算法实现

2013年03月31日 186KB 下载

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

不良信息举报

编写一个函数,实现两分法查找算法。

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭