题目

小刘在研究n个数的冒泡排序算法,发现可以从两个方面进行优化: 1)在每遍冒泡过程中,若最后一次交换的是last与last-1位置的数,则last位置之前的相邻数据均已有序。进行下一遍冒泡,无序区域设置为[last,n],每一遍排序均可能使当前的无序区域缩小。 2)若在某一遍排序中没有数据交换,说明待排序数据都已经有序,冒泡排序过程可在此遍排序后结束。因此可以引入一个变量lag,记录在每遍排序过程中是否发生了交换。 小刘按上述方法设计了一个冒泡优化VB程序功能如下:单击“生成数据”按钮 Command1后,随机生成一组无重复的两位整数存入数组a,并显示在列表框List1中。单击“排序”按钮Command2后,将数组a中的数据进行降序排序,排序后的数据显示在列表框List2中,排序过程中实际的冒泡遍数显示在Label3中。程序运行界面如图所示。实现上述功能的VB程序如下,回答下列问题。 (1) 若按优化后的冒泡排序算法,数据28,15,10,8,12进行降序排序,冒泡的遍数是(填数字)。 (2) 在划线处填入合适的代码。 Dim a (1 To 20) As Integer Private sub command1_Click ( )    ‘ 随机生成不重复的两位数 Dim i As Integer, j As Integer List1, Clear : List2. Clear Randomize For i = 1 To 20   a(i) = Int (Rnd*90) + 10   For j = 1 To i-1     If     ①       Then i =i-1:Exit For   Next j Next i For i=1 To 20   List1.AddItem Str(a(i)) Next i End Sub Private Sub Command2_ Click ( ) Dim flag As Boolean, i As Integer, j As Integer Dim temp As Integer, num As Integer, last As Integer num = 0 : last = 1 flag= True Do While flag=True          ②        For j = 20 To last +1   Step -1     If a(j) > a(j-1) Then       temp =a(j):a(j) = a(j-1): a(j-1) = temp              ③             flag = True ' 有交换发生     End if   Next j   num = num +1 Loop For i =1 To 20   List2 AddItem Str(a(1) Next i Label13. Caption = "本次排序的冒泡遍数为:" & str(num) End sub ① ② ③  答案: 【1】2 【1】a(i)=a(j)【2】flag= False【3】last=j
信息技术 试题推荐
最近更新