冒泡排序(英语: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
冒泡排序的效率仅仅取决于列表中元素的个数,与元素的值和初始序列无关。