Advertisement
karlakmkj

Bubble sort

Jan 6th, 2021
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.59 KB | None | 0 0
  1. def sort_with_bubbles(lst):
  2.     swap_occurred = True
  3.  
  4.     while swap_occurred:
  5.         swap_occurred = False
  6.         for i in range(len(lst) - 1):
  7.             if lst[i] > lst[i + 1]:
  8.              # The goal of the swap is to store a number to a temporary variable so that we can change that variable and preserve the value. To do that, we need to copy the list item to temp first:
  9.                 temp = lst[i]
  10.                 lst[i] = lst[i + 1]
  11.                 lst[i + 1] = temp
  12.                
  13.                 swap_occurred = True
  14.     return lst
  15.  
  16. print(sort_with_bubbles([5, 3, 1, 2, 4]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement