Bubble Sort & Insertion Sort Step-by-Step in Python

⚡ Direct Answer & Key Takeaway

Bubble Sort repeatedly compares adjacent pairs `arr[j]` and `arr[j + 1]`, swapping out-of-order elements so the largest remaining value bubbles to the end after each pass. Insertion Sort picks `key = arr[i]` and shifts larger sorted elements right until `key` lands in position. Both are stable, in-place O(n²) worst-case algorithms requiring O(1) space, and both achieve O(n) best-case time on nearly sorted lists (with Bubble Sort's `swapped` flag).

1. Bubble Sort Pass Mechanics and Early-Exit Optimization

In NCERT Class 12 Computer Science, Bubble Sort runs `n - 1` outer passes (`i` from `0` to `n - 2`). On pass `i`, the inner loop `for j in range(0, n - i - 1):` compares neighbors and swaps them via Python tuple unpacking `arr[j], arr[j + 1] = arr[j + 1], arr[j]` whenever `arr[j] > arr[j + 1]`. Notice the shrinking upper bound `n - i - 1`: after `i` passes, the last `i` elements are already locked in their final sorted positions, so re-checking them wastes comparisons. Adding a `swapped = False` boolean at the start of each outer pass and breaking immediately when no swaps occur optimizes best-case time on an already sorted list from `O(n²)` down to `O(n)` without sacrificing simplicity.

  • `n - 1` outer passes guarantee sorting an `n`-element list completely.
  • Inner loop bound `n - i - 1` skips the `i` largest elements already settled at the right tail.
  • A `swapped` flag cuts already-sorted runtime to a single `O(n)` pass.

2. Insertion Sort Shifting Logic vs. Repeated Swapping

Insertion Sort divides the list into a growing sorted prefix `arr[0..i-1]` and an unsorted suffix `arr[i..n-1]`, starting at `i = 1`. In each pass, it saves `key = arr[i]` and walks backward with `j = i - 1` using `while j >= 0 and arr[j] > key:`. Instead of performing three-assignment swaps at every step, it simply shifts larger elements one slot right via `arr[j + 1] = arr[j]` and decrements `j`. Once the loop stops, `arr[j + 1] = key` drops `key` into its exact sorted slot. Because each pass only shifts elements strictly greater than `key` (never `>=`), equal values preserve their original relative order—making Insertion Sort stable and significantly faster than Bubble Sort in practice. On reverse-sorted input of length `n`, it performs `n(n - 1)/2` comparisons and shifts.

  • Store `key = arr[i]` before shifting so overwriting `arr[i]` does not lose the value.
  • Check `j >= 0` before `arr[j] > key` in the `while` condition to leverage Python short-circuiting.
  • Shifting uses one assignment per step instead of three assignments per Bubble Sort swap.

3. Board Trace Strategy and Comparison Summary

CBSE 3-mark and 5-mark sorting questions frequently give a 5- or 6-element list such as `[29, 10, 14, 37, 13]` and ask you to show the list state after every outer pass. Always distinguish the two algorithms when writing dry runs: Bubble Sort fixes the right-hand tail element by element after each pass, whereas Insertion Sort grows a locally sorted prefix on the left while leaving trailing elements untouched until their turn arrives. Also pay attention to loop invariants: in Bubble Sort, pass 1 guarantees the global maximum is at index `n - 1`; in Insertion Sort, pass `i` guarantees `arr[0..i]` is sorted relative to itself, though global maximums may shift later. Both mutate the original list in-place, so copy first with `arr.copy()` if you need to preserve input.

  • In Bubble Sort, elements settle from right to left (largest first).
  • In Insertion Sort, the sorted prefix expands from left to right one item per pass.
  • Both algorithms sort in-place using `O(1)` extra memory and preserve equal-key order.

4. Step-by-Step Pass Tracer for Bubble Sort and Insertion Sort

def bubble_sort_trace(nums):
    arr = nums.copy()
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        print(f"Bubble Pass {i + 1}: {arr}")
        if not swapped:
            break
    return arr

def insertion_sort_trace(nums):
    arr = nums.copy()
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
        print(f"Insertion Pass {i}: {arr}")
    return arr

sample = [29, 10, 14, 37, 13]
bubble_sort_trace(sample)
insertion_sort_trace(sample)

Verified Console / Dry-Run Output:

Bubble Pass 1: [10, 14, 29, 13, 37]
Bubble Pass 2: [10, 14, 13, 29, 37]
Bubble Pass 3: [10, 13, 14, 29, 37]
Bubble Pass 4: [10, 13, 14, 29, 37]
Insertion Pass 1: [10, 29, 14, 37, 13]
Insertion Pass 2: [10, 14, 29, 37, 13]
Insertion Pass 3: [10, 14, 29, 37, 13]
Insertion Pass 4: [10, 13, 14, 29, 37]

5. Bubble Sort vs. Insertion Sort Complexity and Behavior Summary

PropertyBubble Sort (Optimized)Insertion SortExam Takeaway
Best-Case TimeO(n) (with swapped flag)O(n) (sorted list)Both finish in one pass on sorted data
Average / Worst TimeO(n²) / O(n²)O(n²) / O(n²)Suitable for small lists or learning traces
Auxiliary SpaceO(1) in-placeO(1) in-placeNo extra array needed beyond temp variables
Data MovementAdjacent swaps (3 writes)Rightward shifts (1 write)Insertion Sort performs fewer writes in practice
StabilityStable (with >)Stable (with >)Equal keys retain original relative positions
🎯 1-on-1 Live Mentorship & Free Study Kit

Practice Sorting Algorithms 1-on-1 at 4Achievers Junior

Write flawless pass-by-pass sorting traces and Python functions for CBSE Class 11-12 CS (083) with 4Achievers Junior (Grades 3-12) in 1-on-1 or 1:4 Micro-Pods.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Using `range(n - i)` instead of `range(n - i - 1)` in Bubble Sort's inner loop, causing an `IndexError` on `arr[j + 1]`.
  • Avoid Mistake: Writing `arr[j] >= key` in Insertion Sort instead of `arr[j] > key`, which breaks stability for duplicate items.
  • Avoid Mistake: Forgetting `j -= 1` inside Insertion Sort's `while` loop, creating an infinite loop.
  • Avoid Mistake: Starting Insertion Sort's outer loop at `i = 0` instead of `i = 1`, wasting an iteration on the single-element sorted prefix.
  • Examiner / Mentor Tip: When asked to sort in descending order in a board exam, change `>` to `<` in the comparison (`arr[j] < arr[j + 1]` or `arr[j] < key`).
  • Examiner / Mentor Tip: In dry-run tables, clearly label Pass 1, Pass 2, and so on—do not merge multiple outer passes into one line.
  • Examiner / Mentor Tip: Mention Python's built-in `sort()` uses Timsort (`O(n log n)`), which combines Merge Sort and Insertion Sort for small runs.

7. Interactive Concept Check Quiz

Question: In Insertion Sort on `[40, 15, 25, 10]`, what is the state of the list immediately after Pass 2 (`i = 2`) completes?

8. Frequently Asked Questions

Why does Bubble Sort need a swapped flag to achieve O(n) best-case time?
Without a `swapped` flag, Bubble Sort always executes `n(n - 1)/2` comparisons even on sorted input, staying O(n²). With `swapped`, Pass 1 sees zero swaps and exits early in O(n) time.
Is Insertion Sort generally faster than Bubble Sort on nearly sorted data?
Yes. When elements are already mostly ordered, Insertion Sort performs far fewer shifts and writes than Bubble Sort performs swaps, and avoids redundant scans without needing an extra flag.
What does it mean that both Bubble Sort and Insertion Sort are stable?
A stable sort preserves the relative order of records with equal keys. Both Bubble Sort (using `>`) and Insertion Sort (using `>`) are stable.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class