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

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

    You need to understand the big Oh notation in order to understand how efficient your algorithm is in terms of usage of computational resources independent of computer architecture or clock rate. It basically helps you analyze the worst case running time or memory usage of your algorithm as the size of the input increases. In summary, the running time of your algorithm will fall into one of these categories (from fastest to slowest);

    O(1): Constant time. Pronounced (Oh of 1). The fastest time.

    O(lg n): Logarithmic time. Pronounced (Oh of log n). Faster than linear time. Traditionally, it is the fastest time bound for search.

    O(n): Linear time. Pronounced (Oh of n, n is the size of your input e.g size of an array). Usually something when you need to examine every single bit of your input.

    O(nlgn): The fastest time we can currently achieve when performing a sort on a list of elements.

    O(n**2): Oh of n squared. Quadratic time. Often this is the bound when we have nested loops.

    O(2**n): Really, REALLY big! A number raised to the power of n is slower than n raised to any power.

    In your case, you are using nested loops which is O(n2). The code i have written uses a single while loop and has a growth complexity of O(n) which is faster than O(n2). I haven't really tried it on a very large array but in your case it seems to work. Try it and let me know if it works as expected.

    k = [7, 0, 3, 4, -1]
    n = len(k)
    i = 0
    count = 0
    while count < n**2: # assuming we wouldn't go through the loop more than n squared times
        if i == n - 1:
            i = 0
            count += 1
            swapped = False
        elif k[i] > k[i+1]:
            temp = k[i]
            k[i] = k[i+1]
            k[i+1] = temp
            i+=1
            swapped = True
        elif swapped == False:
            i += 1
        elif swapped == True and i < n - 1:
            i += 1
    

    Note: In the example list (k), we only need to loop through the list three times in order for it to be sorted in ascending order. So if you change the while loop to this line of code while count < 4:, it would still work.

提交回复
热议问题