最新消息:

VB_Python代码对照算法百题(014)

Python 少儿编程 1617浏览 0评论

VB_Python代码对照算法百题(014)

VB代码(2017年11月浙江)16.小李基于冒泡排序算法编写了一个VB程序,功能如下:在文本框Text1中显示排序前的数据,单击“排序”按钮Command1,在文本框Text2中显示剔除重复数据后的升序排序结果。程序运行界面如下图所示。 

VB_Python代码对照算法百题(014) 

实现上述功能的VB程序如下,但加框处代码有错,请改正。 

Const n = 10 

Dim a(1 To n) As Integer 

Private Sub Command1Click()

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

参考答案:

(1)<a(j-1)或 style=”box-sizing: border-box;”>a(j)<a(j-1) 或 a(j-1) > a(j)

(2)a(j)=a(bottom) 或 t=a(j):a(j)=a(bottom):a(bottom)=t

<a(j-1)或 style=”box-sizing: border-box;”>解析:

<a(j-1)或 style=”box-sizing: border-box;”>  冒泡排序去重复数据处理,处理后仅有序输出不重复部分,相邻两数据进行比较,可结合交换语句“t = a(j): a(j) = a(j – 1): a(j – 1) = t” 确定比较的是a(j)和a(j – 1),再观察程序执行界面,输出的数据为升序,可确定当a(j) < a(j – 1)时进行向前交换。 结合语句“ElseIf a(j) = a(j – 1) Then”及注释语句“相邻两个数据相等,进行剔除处理”,可确定是对相邻重复数据进行处理,方法是如果元素a(j-1)与a(j)元素值相同,将最末端元素前移,覆盖a(j),然后执行“bottom = bottom – 1”,此时数组元素个数减1,数组底端下标:bottom-1,底端数据已经前移,无需再参与排序,则可确定答案为a(j) = a(bottom)。

  首先通过题干描述,分析清楚算法思想,即该算法要做什么,如何实现!并划出解题的主要关键词,例如此题中主要关键词为“显示剔除重复数据后的升序排序结果”,注意程序中的注释语句所提供信息。

<a(j-1)或 style=”box-sizing: border-box;”>  此题中进行剔除处理时“a(j) = a(j – 1)”,在进行覆盖剔除处理时不能将“a(j - 1) = a(bottom)”,因为在继续比较时,比较的数据应该是a(j)或a(j – 1)中原来数据,且a(j – 1)将作为下次比较中新的“a(j)”继续比较。

<a(j-1)或 style=”box-sizing: border-box;”>Python代码:

<a(j-1)或 style=”box-sizing: border-box;”>a=[17,12,17,10,16,15,10,17,9,16]

<a(j-1)或 style=”box-sizing: border-box;”>print(‘排序前数据:’,a)

<a(j-1)或 style=”box-sizing: border-box;”>a.sort()

<a(j-1)或 style=”box-sizing: border-box;”>b=a[:]

<a(j-1)或 style=”box-sizing: border-box;”>for i in range(9):

<a(j-1)或 style=”box-sizing: border-box;”> if a[i]==a[i+1]:

<a(j-1)或 style=”box-sizing: border-box;”>   b.remove(a[i+1])

<a(j-1)或 style=”box-sizing: border-box;”>print(‘排序后数据:’,b)

<a(j-1)或 style=”box-sizing: border-box;”>VB_Python代码对照算法百题(014)

Python代码运行结果:

<a(j-1)或 style=”box-sizing: border-box;”>VB_Python代码对照算法百题(014)

您必须 登录 才能发表评论!