python3-- bubble sort

Bubble Sort

Bubble sort (English: Bubble Sort) is a simple sorting algorithm. It repeatedly traverse the number of columns to be sorted, a comparison of two elements, if they put them in the wrong order switching over. Traversing the series of work is repeated until there is no longer need to swap, that is to say the number of columns already sorted completed. The origin of the name of the algorithm is because the smaller elements will slowly through the exchange of "float" to the top of the columns.

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.

 

Analysis bubble sort

 

 

Code

. 1  DEF bubble_sort (alist):
 2      for J in Range (len (alist) -. 1, 0, -1 ):
 . 3          # J represents the number of comparisons needed each pass is gradually decreased 
. 4          for I in Range (J ):
 . 5              IF alist [I]> alist [I +. 1 ]:
 . 6                  alist [I], alist [I +. 1] = alist [I +. 1 ], alist [I]
 . 7  
. 8  
. 9 Li = [54 is, 26 is, 93,. 17, 77, 31 is, 44 is, 55, 20 is ]
 10  bubble_sort (Li)
 . 11  Print (Li)   # [. 17, 20 is, 26 is, 31 is, 44 is, 54 is, 55, 77, 93]
View Code

 

time complexity

  • Optimal time complexity: O (n) (represented traversal time that no elements can be exchanged, sorting ends.)
  • The worst time complexity: O (n2)
  • Stability: Stable

Guess you like

Origin www.cnblogs.com/tom-blogs/p/11312142.html