Exercise #42: Bubble Sort
def bubbleSort(numbers):
# The outer loop loops i over all but the last number:
for i in range(len(numbers) - 1):
# The inner loop loops j starting at i to the last number:
for j in range(i, len(numbers)):
# If the number at i is greater than the number at j, swap them:
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
# Return the now-sorted list:
return
numbers
152
A B O U T T H E A U T H O R
Al Sweigart
is a software developer, fellow of the Python Software Foundation, and author of
several programming
books with No Starch Press, including the worldwide bestseller Automate the
Boring Stuff with Python. His last name rhymes with ―why dirt.‖ His Creative Commons licensed
works are available at
https://www.inventwithpython.com. His cat Zophie weighs 10 pounds.
al@inventwithpython.com
https://alsweigart.com
https://twitter.com/AlSweigart
https://github.com/asweigart
https://www.youtube.com/user/Albert10110
https://www.patreon.com/AlSweigart
Black Lives Matter
Trans Rights Are Human Rights