在Python3.6中打印Bubble排序的每个阶段

时间:2019-04-30 12:28:26

标签: python-3.x

使用冒泡排序对给定的一组数字进行排序。输入的第一行包含元素的数量,输入的第二行包含要排序的数字。在输出中以给定格式打印第3次迭代时数组的状态以及最终排序的数组

alist=[]
def bubble_sort(alist):
    for i in range(len(alist) - 1, 0, -1):
        no_swap = True
        for j in range(0, i):
            if alist[j + 1] < alist[j]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
                no_swap = False
        if no_swap:
            return
n=int(input()) 
for i in range(n):
    alist.append(int(input()))
alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
    print(i,end=" ")

测试用例1

7

64

34

25

12

22

11

90

预期输出: 它应该打印以下三行

12 22 11 25 34 64 90

排序数组:

11 12 22 25 34 64 90

测试用例2

8

14

83

25

47

9

77

1

0

预期输出: 它应该打印以下三行

14 9 25 1 0 47 77 83

排序数组:

0 1 9 14 25 47 77 83

1 个答案:

答案 0 :(得分:0)

只需在您的for循环中添加一次打印,即可达到第三次迭代

alist=[]
def bubble_sort(alist):
    number_of_iterations = 0
    for i in range(len(alist) - 1, 0, -1):
        no_swap = True
        for j in range(0, i):
            if alist[j + 1] < alist[j]:
                alist[j], alist[j + 1] = alist[j + 1], alist[j]
                no_swap = False
        if i == len(alist) - 3:
            print(*alist) # Using the unpacking operator for pretty print, if you are in python2 you can print it this way : " ".join(map(str, alist))
        if no_swap:
            return
n=5
alist = [7, 64, 34, 25, 12, 22, 11, 90]
bubble_sort(alist)
print('Sorted array: ', end='\n')
for i in alist:
    print(i,end=" ")