排序python泡沫两者

时间:2018-05-16 08:12:13

标签: python sorting

我正在编写一个名为bubble_both的双向冒泡排序函数。在每次通过列表时,方向都会发生变化。因此,在第一次传递后,最大值位于正确的位置,在第二次传递后,最小值位于正确的位置,依此类推。

一旦传球中没有掉头,排序就会结束。

该函数应该每次通过一个传递打印列表,并在该传递中进行比较次数和交换次数,如下例所示: Example

以下是我的尝试,但似乎有一些错误:

def bubble_both(a_list):
   exchanges = True
   pass_num = len(a_list) - 1
   while pass_num > 0 and exchanges:
       exchanges = False
       for i in range(pass_num):
           if a_list[i] > a_list[i + 1]:
               exchanges = True
               a_list[i], a_list[i + 1] = a_list[i + 1], a_list[i]
       pass_num = pass_num - 1

1 个答案:

答案 0 :(得分:0)

在我看来,您的代码运行良好,因为它正确地对数据进行排序。但对我来说,它看起来像一个简单的单向排序。问题陈述要求bubble_both()函数在进行报告时打印出进度报告。代码中没有print()调用,因此您看不到进度报告。但是在调用函数之后,变量a_list实际上是排序的。我添加了print()调用作为函数的第一行,这就是我得到的:

>>> a_list
[54, 26, 93, 17, 77, 31, 44, 55, 20]
>>> bubble_both(a_list)
[54, 26, 93, 17, 77, 31, 44, 55, 20]
[26, 54, 93, 17, 77, 31, 44, 55, 20]
[26, 54, 17, 93, 77, 31, 44, 55, 20]
[26, 54, 17, 77, 93, 31, 44, 55, 20]
[26, 54, 17, 77, 31, 93, 44, 55, 20]
[26, 54, 17, 77, 31, 44, 93, 55, 20]
[26, 54, 17, 77, 31, 44, 55, 93, 20]
[26, 54, 17, 77, 31, 44, 55, 20, 93]
[26, 17, 54, 77, 31, 44, 55, 20, 93]
[26, 17, 54, 31, 77, 44, 55, 20, 93]
[26, 17, 54, 31, 44, 77, 55, 20, 93]
[26, 17, 54, 31, 44, 55, 77, 20, 93]
[26, 17, 54, 31, 44, 55, 20, 77, 93]
[17, 26, 54, 31, 44, 55, 20, 77, 93]
[17, 26, 31, 54, 44, 55, 20, 77, 93]
[17, 26, 31, 44, 54, 55, 20, 77, 93]
[17, 26, 31, 44, 54, 20, 55, 77, 93]
[17, 26, 31, 44, 20, 54, 55, 77, 93]
[17, 26, 31, 20, 44, 54, 55, 77, 93]
[17, 26, 20, 31, 44, 54, 55, 77, 93]
[17, 20, 26, 31, 44, 54, 55, 77, 93]

代码不会将交换计为问题陈述。它只使用一个真/假标志。所以我没有尝试打印出来。