Selection Sort and Insertion Sort
Compare how each method grows a sorted prefix: select its next value or insert a new value into it.
Core Intuition & How It Works
Selection sort repeatedly selects the smallest remaining element to place at the front, while insertion sort inserts each new element into its proper spot in an already-sorted prefix. Both are O(n²) worst case, but insertion sort runs in O(n) on nearly sorted data.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n²) worst, O(n) insertion best |
| Space Complexity | O(1) |
| Topic Chapter | Chapter 9: Sorting & Selection |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Use insertion sort for tiny subarrays (n ≤ 32) or almost-sorted inputs—hybrid sorts like Timsort and Introsort rely on it.
Common Pitfalls & Edge Cases
Assuming selection sort is stable (swapping distant elements can reorder equal keys, whereas insertion sort is stable).
Real-World & Technical Interview Applications
Base case inside hybrid production sorts (Timsort, PDQSort), online card-hand sorting, and embedded tiny arrays.