📄 frmbinarysearch.frm
字号:
VERSION 5.00
Begin VB.Form frmBinarySearch
Caption = "Binary Search"
ClientHeight = 3195
ClientLeft = 60
ClientTop = 345
ClientWidth = 4680
LinkTopic = "Form1"
ScaleHeight = 3195
ScaleWidth = 4680
StartUpPosition = 3 '窗口缺省
Begin VB.CommandButton cmdBinarySearch
Caption = "BinarySearch"
Height = 2685
Left = 210
TabIndex = 0
Top = 210
Width = 4185
End
End
Attribute VB_Name = "frmBinarySearch"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Private Sub cmdBinarySearch_Click()
Dim a&(10)
Dim iFoundPosition%
Dim x As Integer
For x = 0 To 9
a(x) = x
Next x
iFoundPosition = BinarySearch(a, UBound(a), 4)
If iFoundPosition = -1 Then
MsgBox "Not found!"
Else
MsgBox "Found " & iFoundPosition
End If
End Sub
'Before using function BinarySearch,you must be sure that the array is sorted in ascending.
Private Function BinarySearch(ByRef ArrayName, ByVal MaxSize As Integer, ByVal SearchValue) As Integer
'ArrayName is array's name.Arguement transfered by array's name which is the address of array's first element
'MaxSize is array's up-bound.Arguement transfered by array's up-bound by function Ubound()
'SearchValue is searched for.Arguement transfered by a constant or a variable which type is variant(Number)
'Function is returned by the position which SearchValue was found.
Dim Low%, High%, Row%
'Low is initialized by array's low-bound.
Low = 0
'High is initialized by array's up-bound.
High = MaxSize
'Loop is starting.
'If Low is fewer than High,exit loop.
Do While Low <= High
'Get average(Integer) of Low and High into Row variable
Row = (Low + High) \ 2
'Decide if SearchValue is found.
Select Case ArrayName(Row)
Case SearchValue
'SearchValue is found,then return the position found to Function,and Exit Function
BinarySearch = Row + 1
Exit Function
Case Is < SearchValue
'SearchValue isn't found,and hints SearchValue is upside of Row
'Re-define the Low and High value
Low = Row + 1
Case Is > SearchValue
'SearchValue isn't found,and hints SearchValue is downside of Row
'Re-define the Low and High value
High = Row - 1
End Select
Loop
'Loop is ending.
'If Function isn't exited insite of loop,hints SearchValue isn't in array.
'Return the position not found to Function
BinarySearch = -1
End Function
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -