vb程序题:分别用冒泡排序法实现有N个元素数组的排序。N由键盘输入,数组元素的值在1~200之间,随机产生
PrivateSubForm_Click()Dima(),i%,imain%,j%,t%n=Val(InputBox(""))ReDima(n-1)Fori=0Ton-1...
Private Sub Form_Click()
Dim a(), i%, imain%, j%, t%
n = Val(InputBox(""))
ReDim a(n - 1)
For i = 0 To n - 1
a(i) = Int(Rnd * 201 + 1)
Next
For i = 0 To n - 1
For j = i + 1 To n - 1 - i
If a(j) > a(j + 1) Then
t = a(j + 1): a(j + 1) = a(j): a(j) = t
End If
Next j
Next i
For i = 0 To n - 1
Print a(i)
Next
End Sub
请在我的答案基础上改正,最好说明改哪里,谢谢 展开
Dim a(), i%, imain%, j%, t%
n = Val(InputBox(""))
ReDim a(n - 1)
For i = 0 To n - 1
a(i) = Int(Rnd * 201 + 1)
Next
For i = 0 To n - 1
For j = i + 1 To n - 1 - i
If a(j) > a(j + 1) Then
t = a(j + 1): a(j + 1) = a(j): a(j) = t
End If
Next j
Next i
For i = 0 To n - 1
Print a(i)
Next
End Sub
请在我的答案基础上改正,最好说明改哪里,谢谢 展开
1个回答
展开全部
运行结果如图:
修改后代码:
Private Sub Form_Click()
Me.Cls
Dim a(), i, j%, t%
Dim n As Integer
n = Val(InputBox(""))
If (n < 2) Then
MsgBox ("请输入大于等于2的整数。") ' 此处加一个验证,防止错误的输入
Exit Sub
End If
ReDim a(n - 1)
For i = 0 To n - 1
a(i) = Int(Rnd * 201 + 1)
Next
For i = 0 To n - 1
For j = i + 1 To n - 1 '你的冒泡算法有问题,已修改
If a(i) > a(j) Then ' 如果要改为降序,把大于号改为小于号即可
t = a(i): a(i) = a(j): a(j) = t
End If
Next j
Next i
For i = 0 To n - 1
Print a(i)
Next
End Sub
追问
你这个不是冒泡排序法,冒泡是要两两比较一致比下去的。你这是选择排序法吧
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询