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