Data Structures & Algorithms Sorting Algorithms
💡
Exercise 54

Bubble Sort 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

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.

# Pass 1: [5, 3, 8, 1] # [3, 5, 8, 1] → swap 5,3 # [3, 5, 8, 1] → 5<8, no swap # [3, 5, 1, 8] → swap 8,1 (8 bubbles to end!) # # Pass 2: [3, 5, 1, 8] # [3, 5, 1, 8] → 3<5, no swap # [3, 1, 5, 8] → swap 5,1 (5 in place!) # # Pass 3: [3, 1, 5, 8] # [1, 3, 5, 8] → swap 3,1 # Done! ✓ [1, 3, 5, 8]

💭 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!

📋 Instructions
Implement `bubble_sort(arr)` that sorts the array in-place. Sort `[64, 34, 25, 12, 22, 11, 90]` and print the result.
Two nested loops. Outer loop runs n-1 times. Inner loop compares arr[j] and arr[j+1], swapping if out of order. Optimization: if no swaps in a pass, array is sorted.
⚠️ Try solving it yourself first — you'll learn more!
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
🧪 Test Cases
Input
bubble_sort([64, 34, 25, 12, 22, 11, 90])
Expected
[11, 12, 22, 25, 34, 64, 90]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.