VB中,随机产生10个0~100之间的随机数,按从小到大的顺序排列怎么做?
可用冒泡排序法:
代码如下:
'不重复随机数排序
'添加 Command1 Command2 Command3Option Explicit Dim i&, j&, k&, t&, Trec&, Arr&(), RndVal&, TmpVal&, S Private Sub Form_Load()
Command1.Caption = "选随机数"
Command2.Caption = "小到大排序"
Command3.Caption = "大到小排序"
'*************************************** 安排控件摆放位置
Me.Move (Screen.Width - Me.Width) \ 2, (Screen.Height - Me.Height) \ 2
1 - 100 之间选 20 个随机数
Trec = 10 End Sub Private Sub Command1_Click() S = GetRnd(1, 100, Trec) Me.Cls
For i = 0 To Trec - 1 Print S(i) Next i End Sub Private Sub Command2_Click()
'********************** 由小排到大(冒泡排序法)
Me.Cls For i = 0 To Trec - 1 k = i For j = i + 1 To Trec - 1 If Arr(k) > Arr(j) Then k = j
Next j t = Arr(i): Arr(i) = Arr(k): Arr(k) = t Print Arr(i) Next i
End Sub Private Sub Command3_Click()
'********************** 由大排到小(冒泡排序法)
Me.Cls For i = 0 To Trec - 1 k = i For j = i + 1 To Trec - 1 If Arr(k) < Arr(j) Then k = j
Next j t = Arr(i): Arr(i) = Arr(k): Arr(k) = t Print Arr(i) Next i End Sub Public Function GetRnd(MinVal&, MaxVal&, Qty&) As Long() Randomize For i = MinVal To MaxVal
ReDim Preserve Arr&(i) Arr(i) = i Next For i = MinVal To MaxVal
RndVal = Int(Rnd * (MaxVal - MinVal + 1)) + MinVal TmpVal = Arr(i)= Arr(RndVal)
Arr(RndVal) = TmpVal Next For i = 0 To Qty - 1 Arr(i) = Arr(i + MinVal) Next GetRnd = Arr()
End Function