1、算法说明
1) 顺序查
逐个元素,如果有,则记录位置,然后跳出循环;否则,查失败。
代码如下:
Private Sub Search(a(), ByVal Key, Index As Integer)
Dim i%
For i = LBound(a) To UBound(a)
If a(i) = Key Then '到,将元素下标保存在index中并结束查
Index = i
Exit Sub
End If
Next i
Index = -1 '若没到,则index值为-1
End Sub
2) ⼆分法查
代码如下:
Private Sub birSearch(a(), ByVal low%, ByVal high%, ByVal Key, index%) Dim mid As Integer
If low > high Then '没有查到
index = -1
计算机二级vbExit Sub
End If
mid = (low + high) \ 2 '取查区间的中点
If Key = a(mid) Then '查到,返回下标
index = mid
Exit Sub
ElseIf Key < a(mid) Then '查区间在上半部分
high = mid - 1
Else
low = mid + 1 '查区间在下半部分
End If
Call birSearch(a, low, high, Key, index) '递归调⽤查函数
End Sub
调⽤⽅法:
Private Sub Command1_Click()
Dim a(11)
a(1) = 5: a(2) = 13: a(3) = 19: a(4) = 21: a(5) = 37
a(6) = 56: a(7) = 64: a(8) = 75: a(9) = 80: a(10) = 88: a(11) = 92
Dim ind As Integer
Call birSearch(a, LBound(a), UBound(a), 21, ind)
Print ind
End Sub
发布评论