VB编程:对数组进行二分查找
运行效果
程序代码
Option Explicit
Dim myarray(100) As Integer '定义数组,下标0-100,数组元素为101个
Private Sub Command1_Click()
Dim low, high, mid, n As Integer
Dim found As Boolean
low = 0
n = 0
high = UBound(myarray)
found = False
mid = CInt((high + low) / 2) '转换为整型,小数部分四舍五入,避免下标出现小数
Do While Not found And (high >= low)
n = n + 1
If CInt(Text1.Text) = myarray(mid) Then ''查找值和当前中间值比较,相等输出
found = True
Label1.Caption = "查询次数:" & n & vbCrLf & _
"查询数值:" & myarray(mid) & vbCrLf & _
"数组下标:" & mid
Exit Do
ElseIf CInt(Text1.Text) < myarray(mid) Then '查找值和当前中间值比较,小了
high = mid - 1
Else '查找值和当前中间值比较,大了
low = mid + 1
End If
mid = CInt((high + low) / 2)
Loop
End Sub
Private Sub Form_load()
Dim i As Integer
For i = 0 To UBound(myarray) '给数组赋值
myarray(i) = i
Print myarray(i)
Next i
End Sub
学习心得
1、二分法查找的思想就是:先取中间值作比较,看大了还是小了,大了就往下取数,小了就往上取数。这样逐步缩小查找范围,就不用每个数都去做比较。适用于有序数组,确实能提高计算效率,是一个很不错的思维方式。