简体   繁体   中英

which code is more efficient in bubble sorting in list (python)

myList = [8, 10, 6, 2, 4] # list to sort
i=4
while i>0:
    for j in range(i):
        if myList[j] > myList[j + 1]:
            myList[j], myList[j + 1] = myList[j + 1], myList[j]
    i-=1
print(myList)

/* ---------------------------------------------------------------------*/

myList = [8, 10, 6, 2, 4] # list to sort
swapped = True # it's a little fake - we need it to enter the while loop

while swapped:
    swapped = False # no swaps so far
    for i in range(len(myList) - 1):
        if myList[i] > myList[i + 1]:
            swapped = True # swap occured!
            myList[i], myList[i + 1] = myList[i + 1], myList[i]

print(myList)

Let's look at both algorithms.
In the first one, we we go through the array fixed number of times. In the second we are iterating array until it is fully sorted.
If there would be a big array, the first algorithm will not sort array completely.
The second one will do it. If the array is sorted initially, the first algorithm will iterate it three times - no mattering about it. The second will iterate one time.

So, the second algorithm is better


A little post-scriptum

Because the task of sorting an array is quite usual, it is implemented as a built-in function. It is using Trimsort , which is better when bubble sort. Python has a good tutorial about it .
Consider using it instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM