Python:如何使我的气泡排序实现更省时? [英] Python: How can I make my implementation of bubble sort more time efficient?
本文介绍了Python:如何使我的气泡排序实现更省时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码-一种气泡排序算法,用于按升序对列表元素进行排序:
Here is my code - a bubble sort algorithm for sorting list elements in asc order:
foo = [7, 0, 3, 4, -1]
cnt = 0
for i in foo:
for i in range(len(foo)-1):
if foo[cnt] > foo[cnt + 1]:
temp = foo[cnt]
c[cnt] = c[cnt + 1]
c[cnt + 1] = temp
cnt = cnt + 1
cnt = 0
我一直在修改自己的代码,但对于在线法官而言,效率仍然太低.一些帮助将不胜感激!
I've been revising my code, but it is still too inefficient for an online judge. Some help would be greatly appreciated!
推荐答案
提早退出 BubbleSort
- The first loop has no bearing on what happens inside
- The second loop does all the heavy lifting. You can get rid of
count
by usingenumerate
- To swap elements, use the pythonic swap -
a, b = b, a
. - As per this comment, make use of an early exit. If there are no swaps to be made at any point in the inner loop, that means the list is sorted, and no further iteration is necessary. This is the intuition behind
changed
. - By definition, after the ith iteration of the outer loop, the last
i
elements will have been sorted, so you can further reduce the constant factor associated with the algorithm.
foo = [7, 0, 3, 4, -1]
for i in range(len(foo)):
changed = False
for j, x in enumerate(foo[:-i-1]):
if x > foo[j + 1]:
foo[j], foo[j + 1] = foo[j + 1], foo[j]
changed = True
if not changed:
break
print(foo)
[-1, 0, 3, 4, 7]
请注意,这些优化都无法改变BubbleSort的渐近(Big-O)复杂度(仍为O(N ** 2)
),而只会降低相关的常数.
Note that none of these optimisations change the asymptotic (Big-O) complexity of BubbleSort (which remains O(N ** 2)
), instead, only reduces the constant factors associated.
这篇关于Python:如何使我的气泡排序实现更省时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文