Bubble sort
As the name implies, the bubble sort intuitively means that the larger the bubble, the faster it will be, and the number that corresponds to the list is the largest one to select, then proceed sequentially.
For example myList = [1,4,5,0,6], the comparison is: the adjacent two numbers first to compare, that is mylist[0] and mylist[1], found not ">" relationship, continue to compare mylist[1] and mylist[2] ... In turn, found mylist[2] > mylist[3] (ie 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 a new list 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]
Example: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6] Bubble sort data
1. For loop
The first type: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]count = 0for J in range (len data): #外层循环15次 for i in range ( Len (data)-1): #内层循环14次 if data[i] > data[i+1]: tmp = data[i+1] data[i+1] = Data[i] data[i] = tmp count + = 1print (data) print ("Count:", Count) #result: [1, 2, 3, 4, 5, 6, 8, ten, one,,, six, four, 54]count:210, second: data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6]count = 0for J in range (1,len (data)): For I in range (len (data)-j): if data[i] > data[i+1]: tmp = data[i+1] data[i+1] = Data[i] data[i] = tmp count + = 1print (dat A) print ("Count:", Count) #result: [1, 2, 3, 4, 5, 6, 8, ten, one,, 54]count:105
Python bubble sort