VB6.0选择法对数组进行排序
在日常生活中经常需要对一组数据按照一定规律进行排列,在Excel就可以按照一定关键字进行升序或者降序排列,接下来介绍如何用VB6.0实现选择法对数组进行排序:
操作方法
- 01
打开VB6.0,新建一个工程,在窗体中添加两个命令按钮,caption分别改为“升序排列”和“降序排列”,添加两个个标签控件,将名字分别改为Lbl1和Lbl2,将窗体Form1的caption属性改为“选择法数组排序”,将界面设置成下图:
- 02
首先产生10个随机数在标签中显示。 双击窗体,在Load事件中写入如下代码: Randomize For i = 1 To 10 a(i) = Int(Rnd * 101 + 100) Lbl1.Caption = Lbl1.Caption & a(i) & " " Next i
- 03
在通用对话框对数组进行定义,使其成为窗体级变量: Dim a(1 To 10) As Integer
- 04
双击“升序排列”命令按钮,进入代码编辑窗口,输入如下代码: For i = 1 To 9 Min = a(i) For j = i + 1 To 10 If a(j) < Min Then Min = a(j) t = a(i): a(i) = a(j): a(j) = t End If Next j Next i Lbl2.Caption = "" For i = 1 To 10 Lbl2.Caption = Lbl2.Caption & a(i) & " " Next i
- 05
双击“降序排列”命令按钮,进入代码编辑窗口,输入如下代码: For i = 1 To 9 Max = a(i) For j = i + 1 To 10 If a(j) > Max Then Max = a(j) t = a(i): a(i) = a(j): a(j) = t End If Next j Next i Lbl2.Caption = "" For i = 1 To 10 Lbl2.Caption = Lbl2.Caption & a(i) & " " Next i
- 06
关闭代码窗口,按下F5运行程序,产生10个随机数,标签中显示10个数:
- 07
单击“升序排列”命令按钮,标签一中的数组按升序排列在标签二中显示,如图:
- 08
单击“降序排列”命令按钮,标签一中的数组按降序排列在标签二中显示,如图: