Bubble sort note three points:
- The first layer loops without looping through all the elements.
- The two-tier loop variable is associated with the first-level loop variable.
- The second loop, finally, must loop through all the elements in the collection.
Example code one:
- The first layer loops, looping only n-1 elements.
- When the first layer of the loop variable is n-1, the second layer loops all elements.
s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]# bubble_sort for in range (0, Len (s)-1) : for in range (i + 1, 0,-1): if s[j] < s[j-1]: -1] = S[j-1], s[j] for in range (0, Len (s)): print(S[m])
View Code
Example code two:
- The first layer loops all elements.
- The second layer also loops through all the elements.
1s = [3, 4, 1, 6, 2, 9, 7, 0, 8, 5]2 3 4 forIinchRange (0, Len (s)):5 forJinchRange (I, 0, 1):6 ifS[J] < S[j-1]:7S[J], s[j-1] = s[j-1], S[j]8 9 forMinchRange (0, Len (s)):Ten Print(S[m])
View Code
Python Bubble Sort