Python Syntax: python-Bubble sorting and python syntax
After that, I said that I needed to collect data on the beauty human body art station. I used python to collect and learn python syntax knowledge. Now I want to share the python Bubble Sorting statements.
Bubble Sort is a simple sorting algorithm. It repeatedly traverses the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The traversal of a Series repeats until there is no need to exchange, that is, the series has been sorted. The name of this algorithm comes from because the smaller elements will slowly "float" to the top of the series through the exchange.
The Bubble Sorting Algorithm operates as follows:
Compares adjacent elements. If the first one is larger than the second one (ascending), the two of them will be exchanged.
Perform the same operation on each adjacent element, from the first to the last. After this step is completed, the final element will be the largest number.
Repeat the preceding steps for all elements except the last one.
Continue to repeat the above steps for fewer and fewer elements until there is no need to compare them.
Code implementation:
1 2 3 4 5 6 7 8 9 10 |
def bubble_sort(alist): for j in range ( len (alist) - 1 , 0 , - 1 ): # J indicates the number of times to be compared for each traversal, which is gradually reduced for i in range (j): if alist[i] > alist[i + 1 ]: alist[i], alist[i + 1 ] = alist[i + 1 ], alist[i] li = [ 54 , 26 , 93 , 17 , 77 , 31 , 44 , 55 , 20 ] bubble_sort(li) print (li) |
Time Complexity
Optimal Time Complexity: O (n) (indicates that no elements can be exchanged during traversal, And the sorting ends .)
Worst time complexity: O (n2)
Stability: Stability