Six ways to put a list in order, with animations, Python code, and easy explanations
Like bubbles rising in a glass of soda, big numbers float to the end!
Picture a row of number cards. Look at the first two cards. If the left one is bigger, swap them. Then move one step to the right and compare the next two. When you reach the end of the row, the BIGGEST number has "bubbled" all the way to the end! Go back to the start and do it again. Each trip through the row moves the next-biggest number into its spot.
💡 Bubble Sort is so slow that computer scientists use it as the classic example of what NOT to do. But it's great for learning!
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr