阅江楼怎么走:高手进来帮忙,关于VB的一个问题!

来源:百度文库 编辑:神马品牌网 时间:2024/07/22 19:36:45
老师布置的2个VB程序设计题,想破头都不知道该怎么做,高手帮忙看下,谢谢!
根据要求分别编两个过程:

(1) 编一个冒泡法排序子过程,对己知的若干个整数按递增次序排列。

[ 提示 ]

子过程形式为:

Sub Sortl(a%())

(2) 编一个二分法查找函数过程,查找某数,找到返回该数在数组中的下标位置,找不到值为 -1 。

函数过程形式为:

Function Searchl(a%() , Key%) As Integer

a%() 为有序的数组, Key% 为要查找的某数。

主调程序可通过随机函数产生若干个数,先后调用 Sort1 子过程和 Search 函数过程。
会做的朋友说个话!

Dim a(0 To 30) As Long '数组的大小只要在这里修改就行了,下面lbound(a)是求数组最小下标,ubound(a)是求数组最大下标
Private Sub setA() '为数组赋值
Dim str As String
Me.AutoRedraw = True
For i = LBound(a) To UBound(a) '
a(i) = Rnd() * 100 Mod 100
str = str & " " & a(i)
Next
Print str
End Sub
Private Sub SortA(a) '冒泡法排序
Dim n As Long, a1 As Long
Dim str As String
n = UBound(a) - 1
For i = n To LBound(a) Step -1
For j = LBound(a) To i
If a(j) < a(j + 1) Then
a1 = a(j)
a(j) = a(j + 1)
a(j + 1) = a1
End If
Next
Next
'显示排序结果
For i = LBound(a) To n + 1
str = str & " " & a(i)
Next
Print str
End Sub
Function Search1(a, key) As Long '二分法查找
Search1 = sch(a, LBound(a), UBound(a), key)
End Function
Function sch(a, n1, n2, key) As Long
Dim n As Long
n = (n1 + n2) \ 2
If a(n) = key Then
sch = n
'Exit Function
End If
If a(n) > key Then
If n + 1 = n1 Then
If a(n1) = key Then
sch = n1
Else
sch = -1
End If
Exit Function
End If
sch = sch(a, n + 1, n2, key)
End If
If a(n) < key Then
If n - 1 = n2 Then
If a(n2) = key Then
sch = n2
Else
sch = -1
End If
Exit Function
End If
sch = sch(a, n1, n - 1, key)
End If
End Function

Private Sub Form_Click()
Dim key As Long
Cls
For i = 0 To 10
setA '为数组赋值
SortA a '冒泡法排序
key = Rnd() * 100 Mod 100 '随机产生一数用二分法查找
Print key & " " & Search1(a, key) '输出查找结果
Next
End Sub

好象有一个随机的函数```有小数点的`