16.【加试题】n个数据的冒泡排序需要经过n-1遍加工,每一遍加工自下而上比较相邻两 个数据,把较小者交换到上面小刘发现:当某一遍加工过程中没有数据交换,说明数据 已经有序,无需进一步加工为此,小刘对算法进行优化,编写了一个 VB 程序,功能如 下:运行程序时,在列表框Listl中显示排序前数据,单击“排序”按钮Commaiidl,在列 表框List2中显示这些数据按升序排序后的结果,在标签Label3中显示排序过程的加工遍 数运行效果如第16题图所示实现上述功能的 VB 代码如下,但加框处代码有错,请改正Dim a(l To 8) As IntegerDim n As IntegerPrivate Sub Form_Load()'n=8,排序前数据存储在数组a中,并在列表框Listl中显示'代码略End SubPrivate Sub Commandl_Click()Dim flag As Boolean ' flag值为True表示一遍加工中发生过交换i = 1flag = TrueDo While i <= n - 1 Or flag = True '( 1)flag = FalseFor j = n To i + 1 Step -1If a(j) < a(j - 1) Thenk = a(j): a(j) = a(j - 1): a(j - 1) = kflag = TrueEnd IfNext ji = i + 1LoopLabel3.Caption ="排序过程的加工遍数为"+ Str(i) ' ( 2)For i = 1 To nList2.AddItem Str(a(i))Next iEnd Sub第 16 题图16.【加试题】小吴为了研究冒泡排序过程中数据的“移动”情况,编写了一个VB程序, 功能如下:在列表框List1中显示排序前数据(存储在数组a中),在文本框Text1中输入 初始位置(即下标值),单击“排序”按钮Zommandl后,在标签Labell中显示指定初始位 置的数据在排序过程中的位置变化情况,排序后的数据显示在列表框List2中。
程序运行界 面如图所示实现上述功能的 VB 程序如下,但加框处代码有错,请改正Dim a(1 To 8) As IntegerDim n As IntegerPrivate Sub Form_Load()a(1)=30:a(2)=47:a(3)=30:a(4)=72a(5) = 70: a(6) = 23: a(7) = 99: a(8) = 24 n = 8For i = 1 To 8List1.AddItem a(i)Next ir鬥探究冒泡排序丨口 |回排序前排序后4? 初卿立置52324303047707299排序位蛊变化情;兄:5- E- 7-> 6End SubPrivate Sub Zommand1_Zlick()Dim i As Integer, j As Integer, k As Integer Dim pos As IntegerDim s As Strings = Text1.Text pos = Val(Text1.Text)For i = 1 To n - 1For j = n To i + 1 Step -1If a(j) < a(j - 1) Thenk = a(j)a(j - 1) = a(j)a(j) = k'如果pos位置的数据参与交换,则更新pos值,记录pos变化位置If pos = j Thenpos = j - 1s = s + ""f"" + Str (pos)Elsepos = js = s + "f" + Str(pos)End IfEnd IfNext jNext iLabel1.Caption = "位置变化情况:" + sFor i = 1 To nList2.AddItem Str(a(i))Next iEnd Sub鬥排序数组元素数组元素的含义排序前數据17 12 17 10 16 15 10 17 916 a(1) |排序 存储班级数na(2)从a(2)到a( 第1、2、•…n+1)依次存储 第n个班级人数排序后数据9 10 12 15 16 17• • •实现上述功能的VB程序如下,但加框处代码 有错,请改正。
Const n 二 10Dim a(1 To n) As Integer Private Sub Command1_Click()a(n+1)a(n+2)• • •• • •从a(n+2)依次存储第1班每 个学生的单科成绩、第2班 每个学生的单科成绩、…第n 班每个学生的单科成绩16.【加试题】小李基于冒泡排序算法编写了一个VB程序,功能如下:在文本框Textl中 显示排序前的数据,单击“排序”按钮Commandl,在文本框Text2中显示剔除重复数据后的 升序排序结果程序运行界面如下图所示Dim i As Integer, j As Integer, t AsIntegerDim bottom As Integer'获取排序前数据依次存储在数组a中,并在文本框Text1中显示代码略 bottom = ni = 1Do While i <= bottom - 1For j 二 bottom To,i + 1 Step -1If a(j)〈 a(i) Thent = a(j): a(j) = a(j - 1): a(j - 1) = tElgelf a(j) = a(j - 1) Then '相邻两个数据相等,进行剔除处理 a(b otto m)=a(j) bottom = bottom - 1End IfNext ji = i + 1 LoopText2.Text = " "For i = 1 To bottomText2.Text = Text2.Text + Str(a(i)) Next iEnd Sub。