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