vb折半法查询,二分法
发布网友
发布时间:2022-04-24 06:29
我来回答
共1个回答
热心网友
时间:2022-06-16 21:10
加两个按钮和两个textbox,text2手动拉宽点,复制以下代码:
Dim vbArr(14) As Long
Dim findcount As Long
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)
'计算查找次数
findcount = 0
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
findcount = findcount + 1
Loop While SearchMax >= SearchMin
End Function
Private Sub Command1_Click()
Dim i As Long
For i = 0 To 14
Randomize
vbArr(i) = Int(Rnd * 100 + 1)
Next i
Dim q As Integer
For i = 0 To 13
For j = i + 1 To 14
If vbArr(i) > vbArr(j) Then
q = vbArr(i): vbArr(i) = vbArr(j): vbArr(j) = q
End If
Next j
Next i
Text2 = ""
For i = 0 To 14
Text2 = Text2 + CStr(vbArr(i)) + " "
Next i
End Sub
Private Sub Command2_Click()
i = vbBinarySearch(vbArr, Val(Text1.Text))
MsgBox "搜索次数:" & CStr(findcount) & vbCrLf & "位置:" & CStr(i + 1)
End Sub
Private Sub Form_Load()
Text1 = ""
Text2 = ""
Command1.Caption = "生成随机数"
Command2.Caption = "二分查找"
End Sub