The bubble sort of python sort algorithm

Source: Internet
Author: User

Bubble sort

As the name implies, the bubble sort intuitively means that the bigger the bubble, the faster it will go: the number that corresponds to our list is the largest of the numbers, and then it's done in turn. For example myList = [1,4,5,0,6], compared in the following way:

The next two numbers are compared first, that is, mylist[0] and mylist[1], found not ">" relationship, will continue to compare mylist[1] and mylist[2] ... In turn, found Mylist[2]>mylist[3] (and 5>0), the exchange, so go through the first full list comparison to get a new list [1,4,0,5,6], and then each scan to get the new list is as follows:

First time: [1,4,0,5,6]

Second time: [1,0,4,5,6]

Third time: [0,1,4,5,6]

Fourth time: [1,4,5,0,6]

Directly on the code:

1 defBubblesort (myList):2     #get the total length of the list first, and prepare for the subsequent loop comparison3Length =Len (myList)4     5     #altogether there were several rounds of list comparisons, which were altogether (length-1) round6      forIinchRange (0,length-1):7         8         #For each round of comparisons, note the change in range, where the length-1-long comparison is required, noting the meaning of-I (can reduce the elements that are already ordered)9          forJinchRange (0,length-1-i):Ten              One             #Exchange A             ifMYLIST[J] > Mylist[j+1]: -TMP =Mylist[j] -Mylist[j]=mylist[j+1] theMYLIST[J+1] =tmp -                  -         #print the list after each round of exchange -          forIteminchmyList: +             Print(item) -         Print("=============================") +  A Print("Bubble Sort:") atMyList = [1,4,5,0,6] -Bubblesort (MyList)

The bubble sort of python sort 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.