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

后端 未结 3 1526
谎友^
谎友^ 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:54

    One easy optimization is to start second loop from i+1 index:

    for i in range(0, len(foo)):
        for j in range(i+1, len(foo)):
            if (foo[i] > foo[j]):
                temp = foo[i]
                foo[i] = foo[j]
                foo[j] = temp
    

    Since you already sorted everything up to index i there is no need to iterate over it again. This can save you more than 50% of comparisons - in this case it's 10 versus 25 in your original algorithm.

提交回复
热议问题