VB编程:对数组进⾏⼆分查-29
运⾏效果
程序代码
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
array在vb什么意思啊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、⼆分法查的思想就是:先取中间值作⽐较,看⼤了还是⼩了,⼤了就往下取数,⼩了就往上取数。这样逐步缩⼩查范围,就不⽤每个数都去做⽐较。适⽤于有序数组,确实能提⾼计算效率,是⼀个很不错的思维⽅式。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论