Python-bubble algorithm, python bubble
Bubble algorithm: For the sequence to be sorted, the two elements are compared each time. If the sorting is incorrect, the two elements are exchanged until the sorting is completed.
Take the series li = [,] 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 lies in that the former is sorted from the beginning to the end, from small values to large values;
The latter is sorted from the back to the back, from the large value, and the last sorted is a small value.
Detailed decomposition using 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 contains six elements, which need to be compared five times. After comparison, a new sequence is obtained. The maximum value is the last one.
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 five to obtain the second largest value.
And so on, we can find that the value in the range is reduced by 1 from len (li-1), so we can set another layer of for loop.
for n in range(1,len(li)-1):
# N is 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