Dim n As Integer ‘存储随机数的个数
Dim f(1 To 100) As Boolean ‘f (i)为true时表示随机整数i已经产生过
Dim a(1 To 100) As Integer ‘依次存放升序排序后的n个随机数
Private Sub Command1_Click() ‘命令按钮“产生随机数并升序排列”的单击事件
Dim i As Integer
Randomize
For i=1 To 100
f(i)=False
Next i
n=Val(Text1. Text)
For i=1 To n
t=Int(Rnd * 100+1)
Do While f(i)=True
t=Int (Rnd * 100+1)
Loop
Next i
j=0
For i=1 To 100 ‘实现排序并输出
If f(i)=True Then
a(j)=i
List1.AddItem Str(i)
End If
Next i
End Sub
Private Sub Command2_Click() ‘命令按钮“查找”的单击事件
Dim key As Integer
key=Val(Text2. Text)
If key <=a(1) Then Label3. Caption=Str(a(1)) : Exit Sub
If key >=a(n) Then Label3. Caption=Str(a(n)) : Exit Sub
L=1: R=n
Do While L <=R ‘找到与key较为接近的两个数a(R)和a(L)
m=(L+R) \2
If key <=a(m) Then
R=m-1
Else
L=m+1
End If
Loop
IfThen ‘在a(R)和a(L)中选出更接近key的数
Label3. Caption=Str(a(R))
Else
Label3. Caption=Str(a(L))
End If
End Sub