Home > Article > Backend Development > Detailed introduction to key points to note in Python bubble sort
This article introduces you to the knowledge of python bubble sorting, involving the main details of bubble sorting. This article explains it to you through example code. The introduction is very detailed and has reference value. Friends who are interested should take a look.
">
Note three points for bubble sorting:
1. It is not necessary to loop through all elements in the first level of loop.
2. Two levels The loop variable is associated with the first-level loop variable.
3. The second-level loop must eventually loop through all elements in the collection.
Sample code one:
1. The first level of loop only loops n-1 elements
2. When the first level loop variable is n-1, the second level loops all elements.
s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
for i in range(0, len(s) - 1):
for j in range(i + 1, 0, -1):
if s[j] < s[j - 1]:
s[j], s[j - 1] = s [j - 1], s[j]
for m in range(0, len(s)):
print(s[m])
Sample code two:
1. The first level loops through all elements.
2. The second level also loops through all elements.
s = [3, 4, 1, 6, 2, 9. , 7, 0, 8, 5]
for i in range(0, len(s)):for j in range(i, 0, -1):
if s[j] < ; s[j - 1]:
s[j], s[j - 1] = s[j - 1], s[j]
for m in range(0, len(s)):
print(s[m])
The above are the key points of the python bubble sort algorithm introduced by the editor. I hope it will be helpful to you. If you have any questions, please Leave me a message and the editor will reply to you in time
The above is the detailed content of Detailed introduction to key points to note in Python bubble sort. For more information, please follow other related articles on the PHP Chinese website!