Bubbling algorithm: For the sequence to be sorted, compare two elements at a time, and if the sort is wrong, swap the two until the sorting is complete.
Take the series Li = [12,22,3,11,8,10] as an example:
For M in range (Len (LI)-1):
For n in range (M+1,len (LI)):
If LI[M] > Li[n]:
temp = Li[n]
Li[n] = Li[m]
LI[M] = Temp
Print Li
Or
For n in range (1,len (LI)-1):
For M in range (Len (LI)-N):
NUM1 = Li[m]
num2 = li[m + 1]
If NUM1 > num2:
temp = Li[m]
LI[M] = num2
Li[m + 1] = Temp
Print Li
The difference between the two is that the former sort from the previous, starting from the beginning of the order of values, the final sort is the large value;
The latter is sorted from the back forward, sorted from a large value, and the last sorted by a small value
Detailed decomposition in the second method
For M in range (5):
NUM1 = Li[m]
num2 = li[m+1]
If NUM1 > num2:
temp = Li[m]
LI[M] = num2
LI[M+1] = Temp
Print Li
The list has 6 elements, which need to be compared 5 times, 22 to compare, to get a new sequence, the largest value ranked in the last.
For M in range (4):
NUM1 = Li[m]
num2 = li[m+1]
If NUM1 > num2:
temp = Li[m]
LI[M] = num2
LI[M+1] = Temp
Print Li
Loop again, since the last element is already the maximum value, you only need to compare the first 5 to get the second largest value.
And so on, you can see that the value in range is reduced by 1 from Len (li-1), so you can set another layer for loop.
For n in range (1,len (LI)-1):
#n为1, 2,3,4,5
#len (LI)-N is 5,4,3,2,1
For M in range (Len (LI)-N):
NUM1 = Li[m]
num2 = li[m + 1]
If NUM1 > num2:
temp = Li[m]
LI[M] = num2
Li[m + 1] = Temp
Print Li
python--bubbling algorithm