Advertisement
acclivity

pyBubbleSort

Oct 31st, 2022 (edited)
767
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. # Bubble Sort.
  2. # Sort a list into ascending order by continually swapping adjacent integers as needed
  3.  
  4. arr = [205, 499, 348, 224, 255, 324, 37, 107, 366, 121, 80, 117, 300, 432, 26, 60, 465,
  5.        395, 199, 402, 9, 290, 450, 40, 111, 28, 319, 363, 48, 318, 259, 351, 312, 159,
  6.        323, 139, 275, 156, 441, 247, 201, 421, 413, 159, 402, 332, 424, 11, 249, 33]
  7.  
  8. swap = True
  9. while swap:                 # Keep repeating this loop until no swaps happen during a complete cycle
  10.     swap = False            # indicate that no swap has happened so far in this pass through the list
  11.     for x in range(len(arr) - 1):
  12.         if arr[x] > arr[x+1]:
  13.             arr[x], arr[x+1] = arr[x+1], arr[x]     # In Python we can swap without using any temporary variable
  14.             swap = True     # Indicate that a swap was done, and so a further pass through the list is needed
  15. print(arr)
  16.  
  17. # Result:-
  18. # [9, 11, 26, 28, 33, 37, 40, 48, 60, 80, 107, 111, 117, 121, 139, 156, 159, 159, 199,
  19. # 201, 205, 224, 247, 249, 255, 259, 275, 290, 300, 312, 318, 319, 323, 324, 332, 348,
  20. # 351, 363, 366, 395, 402, 402, 413, 421, 424, 432, 441, 450, 465, 499]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement