Python bubble sort points to note in detail

  • 2020-05-10 18:23:30
  • OfStack

3 points to note about bubble sorting:

1. The layer 1 loop does not need to cycle all elements.

2. The loop variables of the two layers are associated with the loop variables of the first layer.

3. Loop at layer 2, and eventually must loop all the elements in the set.

Example code 1:

1. Loop in layer 1, only n-1 elements are cycled.

2. When the loop variable in layer 1 is n-1, all elements in layer 2 are cycled.


s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]
# bubble_sort
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])

Example code 2:

1. Loop through all elements at layer 1.

2. Layer 2 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])

Related articles: