对数组a中的n个元素进行排序,生成左右交替上升的数据序列,结果如下表所示:
a(1) | a(2) | a(3) | …… | a(n-2) | a(n-1) | a(n) |
27 | 35 | 39 | …… | 49 | 39 | 33 |
小华由此设计一个VB程序,功能如下:单击“排序”按钮Command1,随机生成10个两位奇数,将随机生成的数据序列显示在文本框Text1中,在文本框Text2中显示完成排序后的数据序列,运行结果如图所示。
Private Sub Command1_Click()
Dim a(1 To 10) As Integer
Randomize
Const n = 10
For i = 1 To n
a(i) = ①
Text1.Text = Text1.Text + Str(a(i))
Next i
For i = 1 To n \ 2
For j = n - i + 1 To i + 1 Step -1
If a(j) < a(j - 1) Then
t = a(j - 1)
②
a(j) = t
End If
Next j
For j = i + 1 To n - i
If Then
t = a(j): a(j) = a(j + 1): a(j + 1) = t
End If
Next j
Next i
For i = 1 To n
Text2.Text = Text2.Text + Str(a(i))
Next i
End Sub