Bubble sort (Bubble sort) is a simple sort algorithm. It iterates over the sequence of columns to be sorted, compares two elements at a time, and if their order is wrong, change them in order.
The work of traversing the sequence is repeated until there is no more element to be exchanged, that is, the sequence is sorted. The algorithm is named because the smaller elements are exchanged and slowly "float" to the top of the sequence.
The bubbling Sort algorithm works as follows:
Compares the adjacent elements. If the first one is larger (ascending) than the second one, they are exchanged for both.
Compare each pair of adjacent elements to do the same work, starting with the first pair to the end. When this is done, the final element will be the maximum number.
Repeat the above steps for all elements, except for the last one.
Continue to repeat the above steps for the remaining elements until there are no pairs of numbers to compare.
We need to do a n-1 bubble process, each corresponding to the number of comparisons as shown:
defBubble_sort (alist): N=Len (alist) forJinchRange (n-1): forIinchRange (0,n-1): ifAlist[i] > Alist[i+1]: alist[i], Alist[i+1] = alist[i+1], Alist[i]if __name__=="__main__": Li= [54, 25, 17, 44, 88, 13, 55, 20, 33] PrintLi Bubble_sort (li)PrintLi
Complexity of Time
Optimal time complexity: O (n) (indicates that traversing a discovery does not have any elements that can be exchanged, the sort ends.) )
Worst time complexity: O (N*n)
Stability: Stable
Python Bubble Sort