VB编程 随机生成10个不等值元素的数组,排成严格升序,从键盘上输入一个整数x,用折半查找法在该
VB编程随机生成10个不等值元素的数组,排成严格升序,从键盘上输入一个整数x,用折半查找法在该数组元素中查找有无等于x的元素,若有则指出其下标,若无则给出找不到的信息...
VB编程 随机生成10个不等值元素的数组,排成严格升序,从键盘上输入一个整数x,用折半查找法在该数组元素中查找有无等于x的元素,若有则指出其下标,若无则给出找不到的信息
展开
2个回答
展开全部
Option Base 1
Const N = 20 '设定随机数上限,如果N>32768,需将数组声明为long型
Sub s()
Dim arr(10) As Integer, tmp As Integer
Dim i As Integer, j As Integer, k As Integer
Randomize
For i = 1 To 10
1: tmp = Int(Rnd * N + 1)
For j = 1 To i - 1
If arr(j) = tmp Then GoTo 1
Next
arr(i) = tmp
Next
For i = 1 To 9
For j = 9 To i Step -1
If arr(j) > arr(j + 1) Then
tmp = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = tmp
End If
Next
Next
i = 1: j = 10
tmp = Application.InputBox("请输入X:", Type:=1)
Do While i < j
k = Int((i + j) / 2)
If arr(k) = tmp Then
MsgBox "X是数组中第" & k & "个数。"
Exit Sub
ElseIf arr(k) > tmp Then
j = k - 1
Else
i = k + 1
End If
Loop
MsgBox "数组中没有X。"
End Sub
展开全部
Dim jz() As Long '定义数组
Private Sub rank(n As Integer, a() As Long) '升序排列过程(冒泡排序法)
For i = 0 To n - 1
flag = 0
For j = n To i + 1 Step -1
If a(j - 1) > a(j) Then
t = a(j - 1): a(j - 1) = a(j): a(j) = t: flag = 1
End If
Next j
If flag = 0 Then Exit For
Next i
End Sub
Private Sub Command1_Click() '生成10个随机数
ReDim jz(9) As Long
For i = 0 To 9
Randomize '随机种子
jz(i) = Int(Rnd * 899) + 100 '生成100-999的随机数
Next i
End Sub
Private Sub Command2_Click() '按升序排序
rank UBound(jz), jz '排序
For i = 0 To UBound(jz) '显示排序后内容
Print jz(i)
Next i
End Sub
Private Sub Command3_Click() '插入新数据
Dim NewN As Long
NewN = Val(InputBox("请输入新数据:"))
If NewN > 0 Then
ReDim Preserve jz(UBound(jz) + 1) As Long
jz(UBound(jz)) = NewN
End If
rank UBound(jz), jz '排序
For i = 0 To UBound(jz) '显示排序后内容数组
Print jz(i)
Next i
End Sub
此法可以多次插入数据
Private Sub rank(n As Integer, a() As Long) '升序排列过程(冒泡排序法)
For i = 0 To n - 1
flag = 0
For j = n To i + 1 Step -1
If a(j - 1) > a(j) Then
t = a(j - 1): a(j - 1) = a(j): a(j) = t: flag = 1
End If
Next j
If flag = 0 Then Exit For
Next i
End Sub
Private Sub Command1_Click() '生成10个随机数
ReDim jz(9) As Long
For i = 0 To 9
Randomize '随机种子
jz(i) = Int(Rnd * 899) + 100 '生成100-999的随机数
Next i
End Sub
Private Sub Command2_Click() '按升序排序
rank UBound(jz), jz '排序
For i = 0 To UBound(jz) '显示排序后内容
Print jz(i)
Next i
End Sub
Private Sub Command3_Click() '插入新数据
Dim NewN As Long
NewN = Val(InputBox("请输入新数据:"))
If NewN > 0 Then
ReDim Preserve jz(UBound(jz) + 1) As Long
jz(UBound(jz)) = NewN
End If
rank UBound(jz), jz '排序
For i = 0 To UBound(jz) '显示排序后内容数组
Print jz(i)
Next i
End Sub
此法可以多次插入数据
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询