search = mid
Else
search = -1
End If
End Function
六、插入法
把一个数插到有序数列中,插入后数列仍然有序
基本思想:n个有序数(从小到大)存放在数组a(1)—a(n)
中,要插入的数x。首先确定x插在数组中的位置P;(可由以下语句实现)
p=1
do while x>a(p) and p<=n
p=p+1
loop
a(p)—a(n)元素向后顺移一个位置以空出a(p)元素放入x,
可由以下语句实现:
for i=n to p step-1
a(i+1)=a(i)
next i
a(p)=x
将其写成一插入函数
Private Sub Instert(a() As Single, x As Single)
Dim p%, n%, i%
n = UBound(a)
ReDim Preserve a(n + 1)
p = 0
Do While x > a(p) And p < =n ' 确定x应插入的位置
p = p + 1
Loop
For i = n To p Step -1
a(i + 1) = a(i)
Next i
a(p) = x
End Sub