⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 74.txt

📁 介绍VB里的各种控件的使用方法,窗口控制,图像编程以及OCX等内容,还提供了一个API集供参考.
💻 TXT
字号:
用两分法搜索列表框或组合框中的数据 

下面的函数能让你在一个已作升序排列的列表框或组合框中查找符合条件的数据。你可以实现精确查找或模糊查找。对这个程序稍微变一下,你就可以在一组已排好序的数组中查找符合条件的数据。该方法的主要好处是对于大量的数据的查找,速度非常之快。例如,一个列表框中有1024条数据,用此法查找只须重复十次,而用传统的方法则要重复512次;如果数据量翻倍,用此法的重复次数为11次,而传统的方法重复的次数也会翻倍。 

Windows API提供了四个消息来实现上述的功能。对于列表框是:LB_FINDSTRING和LB_FINDSTRINGEXACT;对于组合框是:CB_FINDSTRING和CB_FINDSTRINGEXACT。但下面的程序则不分列表框和组合框,只要事先对其中的数据排序即可。 代码如下: 

?
Function FindExact(Control As Control, Searched As String, _
    Optional StartingIndex As Variant)

Dim I As Long, j As Long, k As Long

FindExact = -1
I = Iif(IsMissing(StartingIndex), 0, StartingIndex)
j = Control.ListCount - 1
Do
    
    If I > j Then Exit Function

    k = (I + j) / 2
 
    Select Case StrComp(Control.List(k), Searched)
         Case 0: Exit Do
         Case -1: I = k + 1
         Case 1: j = k - 1
    End Select
Loop


Do While k > 0
    If StrComp(Control.List(k - 1), Searched) Then
        Exit Do
    End If
    k = k - 1
Loop
FindExact = k

End Function


Function FindPartial(Control As Control, Searched As String, _
    Optional StartingIndex As Variant)
Dim I As Long, j As Long, k As Long, lun As Long

FindPartial = -1
I = Iif(IsMissing(StartingIndex), 0, StartingIndex)
j = Control.ListCount - 1
lun = Len(Searched)
Do
    
    If I > j Then Exit Function

    k = (I + j) / 2
    
    Select Case StrComp(Left(Control.List(k), lun), Searched)
        Case 0: Exit Do
        Case -1: I = k + 1
        Case 1: j = k - 1
    End Select
Loop


Do While k > 0
    If StrComp(Left(Control.List(k - 1), lun), Searched) Then
     Exit Do
    End If
    k = k - 1
Loop
FindPartial = k

End Function
程序用法如下:

Index = FindExact(Control, Searched[, StartingIndex]) 
Index = FindPartial(Control, Searched[, StartingIndex])

其中Control代表列表框或组合框的名称,Searched表示搜索条件,StartingIndex为可选参数,表示从哪里开始搜索。函数的返回值为符合条件的数据的索引值。如果未找到符合条件的数据,则返回值为-1.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -