Python-bubble algorithm, python bubble

Source: Internet
Author: User

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

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.