Python Fifth: Bubbling algorithm, System standard module

Source: Internet
Author: User

One: The bubbling algorithm, also called bubble sort, features the following:

1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.

2. Do the same work for each pair of adjacent elements, starting from the first pair to the end of the last pair. At this point, the last element should be the maximum number.

3. Repeat the above steps for all elements except the last one.

4. Repeat the above steps each time for fewer elements until there are no pairs of numbers to compare.

Use Python's bubbling sort to complete the sorting of a set of unordered queues:

data = [10,4,33,21,54,3,8,11,5,22,2,2,2,1,17,13,6]Print(Data,"Original Queue") forJinchRange (1,len (data)-2):#cycle, the total length of the list queue is reduced by 2, because the following comparisons are two subscript bits backwards based on the subscript of the element     forIinchRange (len (data)-j):#The number of times a small loop is subtracted from the number of times that cycle has been cycled, because cycle will have one of the largest elements on the far right once per loop, and the secondary element will not need to be looped.        ifData[i] > Data[i+1]:#false into the first element is greater than the second elementTMP = data[i+1]#The first step is to save the second element to a temporary variableDATA[I+1] = Data[i]#The second step puts the value of the second element equal to the value of the previous larger elementData[i] = tmp#The third step is to place the previous element equal to the temporary variable of the smaller element behind it, thus completing the position substitutionPrint(Data,"the queue after bubbling sort") Execution Result: [10, 4, 33, 21, 54, 3, 8, 11, 5, 22, 2, 2, 2, 1, 17, 13, 6] Original queue [1, 2, 2, 2, 3, 4, 5, 6, 8, 10, 11, 13, 17, 21, 22, 33, 54] bubble sorted queue

Python Fifth: Bubbling algorithm, System standard module

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.