在VB中用折半查找法查找

来源:百度知道 编辑:UC知道 时间:2024/06/20 05:29:59
用此法在一有序数组中查找一个元素,在TEXT1中显示一个有序数组,在TEXT2中输入要查找的数,单击"查找"按钮开始查找,若能在数组中找到输入的数则在TEXT3中显示该数在数组中的位置(在该数组中的第几个数,从1开始)否则弹出对话框消息对话框要查找的数不在数组中.

Dim arr

Private Sub Command1_Click()
low = 0
high = 9
x = -1
a = Int(Text2.Text)
Do While low <> high
n = (low + high) \ 2
If a = arr(n) Then
x = n
Exit Do
ElseIf a > arr(n) Then
low = n
Else
high = n
End If
Loop
If x >= 0 Then Text3.Text = x + 1 Else MsgBox "要查找的数不在数组中"
End Sub

Private Sub Form_Load()
arr = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Text1.Text = Join(arr)
End Sub