'二分查找算法PrivateSub Command1_Click()Dim i%, m%, n%
Dim x(1To10)AsSingleFor i =1To10
x(i)=Val(InputBox("请输入"))Next i
Call bubbleSort(x)For i =LBound(x)ToUBound(x)'LBound(x)和UBound(x)是用于获取数组x的下界和上界的函数。LBound(x)返回数组x的最小索引(即下界),UBound(x)返回数组x的最大索引(即上界)Print x(i);'加逗号的目的是其显示为一行数据Next i
Print'\n'For i =1To5
n =Val(InputBox("请输入你要查找的值"))
m = binarySearch(x, n)If(m =1)ThenPrint"已找到"ElsePrint"未找到"EndIfNext i
EndSubFunction binarySearch(arr!(), key) As IntegerDim low%, high%,mid%, p AsBoolean
p =False
low =LBound(arr)
high =UBound(arr)DoWhile(low <= high)mid=(low + high) \ 2If arr(mid)=keyThen
p =True
binarySearch =1ExitDoElseIf arr(mid)<keyThen
low =mid+1Else
high =mid-1EndIfLoopIf p =FalseThen binarySearch =-1EndFunctionSub bubbleSort(arr!()) '通过arr!()表示arr是一个数组,并且!()表示该数组是在子程序调用时传递给它的Dim i%, j%
For i =UBound(arr)ToLBound(arr)Step-1'这里的意思是从最大索引数10开始递减到最小索引数1For j =1To i -1'i到了1就会由于这个语句1无法正着到0,所以首先退出这里的循环If arr(j)> arr(j +1)ThenCall mySwap(arr(j), arr(j +1))EndIfNext j
Next i '当最后一步退出上一个循环后,i到了这个语句变为0,这样就不符合从10到1,也就退出了最外层的循环。EndSubSub mySwap(ByRef a,ByRef b)Dim c As Variant
c = a
a = b
b = c
EndSub