Interview essential algorithm | graphical bubble sorting (Python)

Bubble sort

The idea of bubble sort

  • Compare adjacent elements . If the first one is bigger than the second one ( Ascending ), Just swap them ;
  • Do the same for each pair of adjacent elements , From the beginning of the first couple to the end of the last couple . After this step , The last element will be the maximum number ;
  • Repeat the above steps for all elements , Except for the last one ;
  • Keep repeating the above steps for fewer and fewer elements each time , Until there's no pair of numbers to compare .

Diagram bubble sort ( The first cycle )

 Insert picture description here

Properties of bubble ordering

  • Optimal time complexity : O ( n ) O(n)% O(n)( Indicates that the traversal finds that there is no exchangeable element , End of sort .)
  • Worst time complexity : O ( n 2 ) O(n^2) O(n2)
  • stability : Stable

Bubble sort code implementation

lst = list(map(int, input().split(',')))
def Bubble_sort(alist):
n = len(alist)
for i in range(0, n - 1):
count = False
for j in range(0, n - 1 - i):
if alist[j] > alist[j + 1]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
count = True
if count == False:
return alist
return alist
Bubble_sort(lst)
Please bring the original link to reprint ,thank
Similar articles