试题

试题 试卷

logo

题型:综合题 题类:常考题 难易度:普通

浙江省高中信息技术 排序算法及程序实现同步练习

小王在研究n个数的冒泡排序算法,发现可以从两个方面进行优化:

⑴在每遍冒泡过程中,若最后一次交换的是last与last-1位置,则last位置之前的相邻数据均已有序。进行下一遍冒泡时,无序区域设置[last, n],这样可使无序区域缩小。

⑵若在某一遍排序中没有数据交换,说明待排序数据都已经有序,冒泡排序过程可在此遍排序后结束。因此可以引入一个变量flag,记录在每遍排序过程中是否发生了交换。

小王设计了如下VB程序,功能如下:按Cominandl“生成数据”后,生成一组随机的两位整数存入数组a,并输出在列表框List1中。单击Command2“排序”后,a中的数据进行降序排序,排序后的数据显示在列表框List2中,排序过程中实际的冒泡遍数显示在Label2上。程序运行界面如下所示。

实现上述功能的VB程序如下,回答下列问题:

(1)、若按小王优化后的冒泡排序算法,数据28,15,10,8,12进行降序排序,冒泡的遍数(填数字)。
(2)、在画线处填入合适的代码。

Dim a(1 To 20) As Integer

Private Sub Commandl_Click()

Dim i As Integer, j As Integer

List1. Clear: List2. Clear

Randomize

For i=1 To 20

 

 For j=1 To i-1

  If a(i)=a(j) Then i=i-1: Exit For

 Next j

Next i

For i=1 To 20

 Listl. Addltem Str(a(i))

Next i

End Sub

Private Sub Commandl2_Click()

Dim flag As Boolean, i As Integer, j As Integer

Dim temp As Integer, nuui As Integer, last As Integer

nuin=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. Addltem Str(a(i))

Next i

Label3. Caption=“本次排序的冒泡遍数为:” & Str (num)

End Sub

举一反三
数组a存储降序排列的m个数据,数组b中存储的是升序排列的n个数据,且两个数组中存储的数据为区间[1,20]范围内的不重复的随机整数。现将两个数组的数据合并到c数组中,使c数组的数据为左右交替上升,如下表所示:

a(1)

a(2)

a(3)

a(4)

a(5)

19

17

6

4

3

a数组

b(1)

b(2)

b(3)

b(4)

b(5)

b(6)

5

7

8

13

15

20

b数组

c(1)

c(2)

c(3)

c(4)

c(5)

c(6)

c(7)

c(8)

c(9)

c(10)

c(11)

3

5

7

13

17

20

19

15

8

6

4

c数组

当窗体Form1加载时,自动产生a、b数组的数据,并分别显示在列表框List1与List2中,单击合并按钮Command1后,在c数组中保存按规则合并后的a、b数组的数据,并显示在列表框List3中。程序截图如下所示:

实现该功能的VB程序如下:

Const m = 5

Const n = 6

Dim a(1 To m) As Integer

Dim b(1 To n) As Integer

Dim c(1 To m + n) As Integer

‘窗体加载时,生成数组a、b中的数据,并按要求排序后显示在列表框中,代码略

Private Sub Command1_Click()

Dim pa As Integer, pb As Integer, pc As Integer, s As Integer, flag As Boolean

pa = m: pb = 1: pc = 1

flag = True

Do While         ①        

    If a(pa) < b(pb) Then

        s = a(pa)

        pa = pa - 1

    Else

        s = b(pb)

        pb = pb + 1

    End If

    c(pc) = s

    If  flag Then

        pc = m + n - pc + 1

    Else

        pc =

    End If

            ②       

Loop

‘处理a、b数组中剩余数据,并在列表框List3中输出数组c,代码略

End Sub

返回首页

试题篮