求VB高手!编写一个程序,功能是:产生10个30~80之间的随机数,用二分法查找52是否在数组中

编写一个程序,功能是:产生10个30~80之间的随机数,用二分法查找52是否在数组中,若查找到输出所在数组下标。若查找不到给出相应信息

'二分法只能对有序数列查找,所以要先排序,再查找,
Private Sub Command1_Click()
Dim data(1 To 100) As Integer
Dim i%, num%
Randomize
For i = 1 To 10
data(i) = Int(Rnd * (80 - 30 + 1) + 30)‘30-80随机数
Print data(i)
Next
num = Val(InputBox("请输入一个数"))
Selectionsort data '排序
i = BinSearch(data, num) '二分函数查找
If i <> -1 Then
MsgBox "找到该数" & i
Else
MsgBox "该数不在数组中"
End If
End Sub
'二分函数
Public Function BinSearch(ByRef data() As Integer, ByVal num As Integer) As Long
Dim lngLow As Long
Dim lngHigh As Long
Dim lngMiddle As Long
lngLow = LBound(data)
lngHigh = UBound(data)
While (lngLow <= lngHigh)
lngMiddle = (lngLow + lngHigh) / 2
If data(lngMiddle) = num Then
BinSearch = lngMiddle
Exit Function
Else
If data(lngMiddle) > num Then
lngHigh = lngMiddle - 1
Else
lngLow = lngMiddle + 1
End If
End If
Wend
BinSearch = -1 '查找失败
End Function
'排序
Sub Selectionsort(data() As Integer)
Dim i As Integer
Dim j As Integer
Dim best_value As Integer
Dim best_j As Integer
For i = 1 To UBound(data) - 1
best_value = data(i)
best_j = i
For j = i + 1 To UBound(data)
If data(j) < best_value Then
best_value = data(j)
best_j = j
End If
Next j
data(best_j) = data(i)
data(i) = best_value
Next i
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-11-25
dim a(9) as integer
dim i as integer
for i=0 to 9
a(i)=(80*rnd()+1)
for i= 0 to 9
if a(i)==52 then
printf(%f,a(i))
end if
next i
相似回答