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

题目:
编写一个函数,实现两分法查找算法。
两分法查找的思想是,首先假设在查找的数字数组中,是按照从小到大的顺序排列的,要查找的关键值首先同中间的元素比较,若相同则查找成功,否则根据这个中间的数与要查找的数的大小关系,保留一半,在数组的另外一半中进行查找,如此重复,每次都到中音的数据去进行比较,每次将减少一半的查找的数据,因此效率比较高。
编写的程序在数组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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值