最新消息:

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

Python 少儿编程 1642浏览 0评论

 VB代码:(2018年8月温州)16.【加试题】有一组正整数,要求仅对其中的奇数进行升序排序。排序后在列表框List2中也仅显示奇数部分数据,结果如图所示。

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

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

Const n = 10

Dim a(1 To n) As Integer

Private Sub Command1_Click()

Dim t As Integer, i As Integer, j As Integer, m As Integer

Dim tmp As Integer

‘读取一组正整数,存储在数组a中,并显示在列表框List1,代码略

i = 1

Do While i <= n

    For j = n To i + 1 Step -1

        If a(j) Mod 2 = 1 Then

            If a(j) < a(j – 1) Then

                tmp = a(j) : a(j) = a(j – 1) : a(j – 1) = tmp

                t = t + 1

            End If

        End If

    Next j

    If a(j) Mod 2 = 0 Then m = m + 1

    i = i + 1

Loop

For i = 1 to m

    List2.AddItem Str(a(i))

Next i

List2.AddItem “一共交换了” & t & “次”

End Sub

参考答案:

(1) (2分) a(j)<a(j-1) Or a(j-1) Mod 2=0<a(j-1) p=”p” or=”” mod=”” style=”box-sizing: border-box;”>

(2) (1分) a(i) Mod 2=1

Python参考代码:

a=[5,55,44,100,34,20,16,13,37,8]

print(‘排序前:’,a)

n=len(a)

t=0

m=0

i=0

while i<n:

    for j in range(n-1,i+1,-1):

        if a[j]%2==1:

            if a[j]<a[j-1] p=”p” or=”” style=”box-sizing: border-box;”>

                a[j],a[j-1]=a[j-1],a[j]

                    t+=1

    if a[i]%2==1:

        m=m+1

    i=i+1

print(‘排序后:’)

for i in range(m):

    print(str(a[i]))

print(‘一共交换了’,t,’次。’)

VB_Python代码对照算法百题(027)Python代码运行结果:

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

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