簡體   English   中英

哪個代碼在列表中的冒泡排序中更有效(python)

[英]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)

讓我們看看這兩種算法。
在第一個中,我們 go 通過數組固定次數。 在第二個中,我們迭代數組直到它完全排序。
如果有一個大數組,第一個算法將不會對數組進行完全排序。
第二個會做。 如果數組最初是排序的,第一個算法將迭代它三次 - 不管它如何。 第二個將迭代一次。

所以,第二種算法更好


一點后記

因為排序數組的任務很常見,所以它被實現為一個內置的 function。它使用Trimsort ,這在冒泡排序時更好。 Python 有一個很好的教程
考慮改用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM