Python: How can I make my implementation of bubble sort more time efficient?

后端 未结 3 1543
谎友^
谎友^ 2021-01-21 15:16

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):
           


        
3条回答
  •  無奈伤痛
    2021-01-21 15:50

    Early Exit BubbleSort

    1. The first loop has no bearing on what happens inside
    2. The second loop does all the heavy lifting. You can get rid of count by using enumerate
    3. To swap elements, use the pythonic swap - a, b = b, a.
    4. 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.
    5. 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]
    

    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.

提交回复
热议问题