python--bubbling algorithm

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.