江苏省VB常用算法(八)查找- - |
VB常用算法(八)查找- -曹苏群 http://caosuqun.bokee.com Tag: 查找 算法
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 Exit 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 Call birSearch(a, LBound(a), UBound(a), 21, Print End Sub 2、实战练习补充代码(2002春二(9)) 张文,机械01 李明,机械01 王文卉,机械01 … 何宇宙,电子02
Option Explicit Option Base 1 Private Sub Form_click() Dim stu() As String, glass() As String, i As Integer Dim n As Integer, name As String, k As Integer Open "c:\stu\stu.txt" For Input As #11 Do While (1) (2) ReDim Preserve stu(n), glass(n) Input #11, stu(n), glass(n) name = InputBox("输入欲查找的学生姓名:") Call search(name, stu, k) If k <= n Then MsgBox (3) Else MsgBox "无此人。" End If Close #11 End Sub Private Sub search(name As String, stu() As String, k As Integer) Dim i As Integer For i = 1 To UBound(stu) If name = stu(i) Then (4) End If Next i (5) End Sub |