vb随机产生范围从1到100的10个整数放在数组a(1to10)中,用选择法将数组中的元素按由小到大顺序输出
1个回答
展开全部
Private Sub Form_Click()
Form1.Cls
Dim i As Integer, j As Integer, temp As Integer, k As Integer
Dim a(1 To 10) As Integer
For i = 1 To 10
a(i) = Int(Rnd * 100 + 1)
Next i
For i = 1 To 10
k = i
For j = i + 1 To 10
If a(k) > a(j) Then k = j
Next j
If (k <> i) Then temp = a(i): a(i) = a(k): a(k) = temp
Next i
For i = 1 To 10
Print a(i);
Next
End Sub
选择法比冒泡法效率更高,在于其引入了变量k,先只变动下标而不是如冒泡法那样temp = a(i): a(i) = a(j): a(j) = temp ,直接交换。
这样减少了temp = a(i): a(i) = a(j): a(j) = temp 执行次数,提高了效率
选择法最多只会交换 n-1 次,n是数列中数的个数(本题中最多9次)
冒泡法一般都会大于n-1次,而且大得多
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询