開心生活站

位置:首頁 > IT科技 > 

冒泡排序python代碼

IT科技1.55W
品牌型號:聯想小新Pro13/系統版本:windows10

冒泡排序(英語:Bubble Sort)是一種簡單的排序算法。它重複地遍歷要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。遍歷數列的工作是重複地進行直到沒有再需要交換,也就是説該數列已經排序完成。

# Sorts a sequence in ascending order using the bubble sort algorithm. def bubbleSort( theSeq ):     n = len( theSeq )     # Perform n-1 bubble operations on the sequence     for i in range( n - 1 ) :         # Bubble the largest item to the end.         for j in range( i + n - 1 ) :             if theSeq[j] > theSeq[j + 1] : # swap the j and j+1 items.                 tmp = theSeq[j]                 theSeq[j] = theSeq[j + 1]                 theSeq[j + 1] = tmp 

冒泡排序的效率僅僅取決於列表中元素的個數,與元素的值和初始序列無關。

冒泡排序python代碼