python write bubble sort


Bubbling is repeatedly traverse the number of columns to be sorted, a comparison of two elements (bubble), if they put them in the wrong order exchange, just like a bubble, like, in order of priority in ascending order.

Bubble sort algorithm operates as follows:

  • Compare adjacent elements. If the first than the second large (in ascending order), the two of them exchanged.
  • Do the same work for each pair of adjacent elements, from the beginning to the end of the first to the last pair. Once this is done, the last element is the biggest number.
  • Repeat these steps for all elements, except the last one.
  • Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.
Wrote three bubble, similar, almost the same expensive, this should be a comment bubble sort, right up to O (∩_∩) O haha ~

1
## The first bubble ## 2A = [2, 9,4,1]#listing . 3n-= len (a)#a list element length =. 4 .n . 4 forIinRange (. 1-n-):#outer loop, the control loop number wheel, n-1 is the index 0 taken from the beginning. (n--. 1 =. 3) . 5 forJinRange (Ni-. 1):#cycle control number (ni-1 = 3) element circulated . 6 IFA [J]> A [J +. 1]:#J = 0 , j + 1 = 1, if the A [0]> A [0 +. 1] . 7 A [J], A [J +. 1] = A [J +. 1], A [J]#compound assignment, if the condition exchange is performed . 8 Print(A) . 9 ## the second bubble ## 10 A = [2,9,4,1] # listing . 11 n-= len (A) # A list element length =. 4 .n 12 is for I in Range (. 1-n-): # outer loop, the control loop number wheel , n-1 is the index starts from 0 taken. (n--. 1 =. 3) 13 is for J in Range (Ni-. 1): # cycle control the number (ni-1 = 3) element loop 14 IF A [J]> A [J +. 1]: # J = 0 , j + 1 = 1, if the a [0]> a [+ 0. 1] 15 # such a manner as in Comparative swap some trouble, not on a one-step 16 JJ = a [j +. 1] # to a [j + 1] is assigned to JJ . 17 A [J + 1] = a [j] # and then a [j] assigned to A [JZ = 1] 18 is a [j] = JJ #Jj and then assigned to A [J] . 19 Print (A) 20 is # # third bubble ## 21 is AA = [2,9,4,1 ] 22 is DEF Sort (AA): # define a function 23 is Print ( ' before ordering: ' ) 24 Print (AA) 25 for I in Range (len (AA) -1 ): 26 is for J in Range (len (AA)-l- I): 27 IF AA [J]> AA [+ J. 1 ]: 28 AA [J], AA [J +. 1] = AA [J +. 1 ], AA [J] 29 Print (' : {} After sorting times ' .format (I +. 1)) # uses a format function 30 Print (AA) 31 is Sort (AA) 32 Print ( ' sorted: ' ) 33 is Print (AA)

Guess you like

Origin www.cnblogs.com/wuzhuangzhuang/p/12119763.html