资源描述
16. 【加试题】n个数据的冒泡排序需要经过n-1遍加工,每一遍加工自下而上比较相邻两个数据,把较小者交换到上面。小刘发现:当某一遍加工过程中没有数据交换,说明数据已经有序,无需进一步加工。为此,小刘对算法进行优化,编写了一个VB程序,功能如下:运行程序时,在列表框List1中显示排序前数据,单击“排序”按钮Commaiid1,在列表框List2 中显示这些数据按升序排序后的结果,在标签Label3中显示排序过程的加工遍数。运行效果如第16题图所示。
实现上述功能的VB代码如下,但加框处代码有错,请改正。
Dim a(1 To 8) As Integer
Dim n As Integer
Private Sub Form_Load()
'n=8,排序前数据存储在数组a中,并在列表框Listl中显示
'代码略
End Sub
Private Sub Command1_Click()
Dim flag As Boolean 'flag值为True表示一遍加工中发生过交换
i = 1
flag = True
Do While '(1) i <= n - 1 Or flag = True
flag = False
For j = n To i + 1 Step -1
If a(j) < a(j - 1) Then
k = a(j): a(j) = a(j - 1): a(j - 1) = k
flag = True
End If
Next j
i = i + 1
Loop
Str(i)
Label3.Caption = "排序过程的加工遍数为" + '(2)
For i = 1 To n
List2.AddItem Str(a(i))
Next i
End Sub
第16题图
16.【加试题】小吴为了研究冒泡排序过程中数据的“移动”情况,编写了一个VB程序,功能如下:在列表框List1中显示排序前数据(存储在数组a中),在文本框Text1中输入初始位置(即下标值),单击“排序”按钮Command1后,在标签Label1中显示指定初始位置的数据在排序过程中的位置变化情况,排序后的数据显示在列表框List2中。程序运行界面如图所示。
实现上述功能的VB程序如下,但加框处代码有错,请改正。
Dim a(1 To 8) As Integer
Dim n As Integer
Private Sub Form_Load()
a(1) = 30: a(2) = 47: a(3) = 30: a(4) = 72
a(5) = 70: a(6) = 23: a(7) = 99: a(8) = 24
n = 8
For i = 1 To 8
List1.AddItem a(i)
Next i
End Sub
Private Sub Command1_Click()
Dim i As Integer, j As Integer, k As Integer
Dim pos As Integer
Dim s As String
s = Text1.Text
pos = Val(Text1.Text)
For i = 1 To n - 1
For j = n To i + 1 Step -1
If a(j) < a(j - 1) Then
k = a(j)
a(j - 1) = a(j)
a(j) = k
'如果pos位置的数据参与交换,则更新pos值,记录pos变化位置
If pos = j Then
pos = j - 1
s = s + "→" + Str(pos)
Else
pos = j
s = s + "→" + Str(pos)
End If
End If
Next j
Next i
Label1.Caption = "位置变化情况:" + s
数组元素
数组元素的含义
a(1)
存储班级数n
a(2)
从a(2)到a(n+1) 依次存储第1、2、…第n个班级人数
…
a(n+1)
a(n+2)
从a(n+2) 依次存储第1班每个学生的单科成绩、第2班每个学生的单科成绩、…第n班每个学生的单科成绩
…
…
For i = 1 To n
List2.AddItem Str(a(i))
Next i
End Sub
16.【加试题】小李基于冒泡排序算法编写了一个VB程序,功能如下:在文本框Text1中显示排序前的数据,单击“排序”按钮Command1,在文本框Text2中显示剔除重复数据后的升序排序结果。程序运行界面如下图所示。
实现上述功能的VB程序如下,但加框处代码有错,请改正。
Const n = 10
Dim a(1 To n) As Integer
Private Sub Command1_Click()
Dim i As Integer, j As Integer, t As Integer
Dim bottom As Integer
'获取排序前数据依次存储在数组a中,并在文本框Text1中显示。代码略
bottom = n
i = 1
Do While i <= bottom - 1
For j = bottom To i + 1 Step -1
If a(j) < a(i) Then
t = a(j): a(j) = a(j - 1): a(j - 1) = t
ElseIf a(j) = a(j - 1) Then ' 相邻两个数据相等,进行剔除处理
a(bottom)=a(j)
bottom = bottom - 1
End If
Next j
i = i + 1
Loop
Text2.Text = " "
For i = 1 To bottom
Text2.Text = Text2.Text + Str(a(i))
Next i
End Sub
展开阅读全文