Bubble Sort is the simplest sorting algorithm. It's slow for big data, but it's great for understanding how sorting works! 🫧
💡 Think of it like this: Imagine bubbles in water — the biggest bubble floats to the top first. In Bubble Sort, the biggest number "bubbles up" to the end of the array in each pass.
How it works: Walk through the array, compare each pair of neighbors, and swap them if they're in the wrong order. Repeat until no swaps are needed.
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Complexity: Time O(n²) worst/average, O(n) best (already sorted with the optimization flag). Space O(1). Never used in production, but essential for learning!
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1): # n-1 passes
swapped = False
for j in range(n - 1 - i): # -i because last i elements are sorted!
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap!
swapped = True
if not swapped: # Optimization: if no swaps, already sorted!
break
return arr
bubble_sort([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]