Insertion Sort
Builds a sorted prefix one element at a time — simple, stable, and great for nearly sorted data.
Insertion Sort is like sorting playing cards in your hand: you take the next card and insert it into the correct position among the cards already in order.
What It Does
Insertion Sort keeps the left side of the list as a sorted prefix. Each iteration takes the next element (the key), shifts larger elements right, and inserts the key into the correct position.
How It Works
- Start with the first element as the sorted prefix.
- Pick the next element as the key.
- Shift elements in the sorted prefix that are larger than the key to the right.
- Insert the key into the gap that remains.
- Repeat until all elements are processed.
Why It’s Useful
Insertion Sort is a great teaching algorithm because the steps are visible and intuitive. It’s also practical for small datasets and nearly sorted inputs, and is commonly used as a “small-case” helper inside faster sorting algorithms.
Performance Notes
- Time: worst-case
O(n²), best-caseO(n)when already sorted. - Space:
O(1)extra space (in-place). - Stable: yes (equal elements keep their original order).
Common Mistakes (Student Pitfalls)
- Not saving the key before shifting values.
- Off-by-one errors when moving left through the sorted prefix.
- Using
>=instead of>and accidentally breaking stability.
Demo / Media
Animation
The animation highlights the sorted prefix, the current key, the shifts to make space, and the final insert step.
UX/UI • Pedagogy • HCI
A short teaching-focused rationale: what I designed, how I structured learning, and the interaction principles behind it.
- Information architecture: definition → steps → notes → pitfalls → demo.
- Visual hierarchy: headings + cards chunk content into “one idea per block.”
- Clear CTA: “Watch Demo” scrolls to the video (low navigation cost).
- Consistency: same layout pattern across all algorithm pages.
- Accessibility: readable type/spacing + native video controls +
playsinline.
- Scaffolded learning: mental model (“cards”) → steps (key/shift/insert) → applications.
- Three-act structure: what it is → how it works → why it matters (+ demo).
- Cognitive load: short steps + chunking reduces overload for beginners.
- Worked example: the demo serves as a guided example learners can replay while practicing.
- Self-check: “Common Mistakes” supports reflection and correction.
- Mental models: “sorted prefix” stays consistent as the key is inserted into place.
- Recognition over recall: repeated terms (key, shift, insert) reduce memorization burden.
- Error prevention: pitfalls highlight off-by-one and stability issues before coding.
- Feedback cues: the demo makes cause → effect visible (shift creates space, insert fixes order).
- Usability heuristics: clarity, consistency, and predictable navigation.
Teaching strategy: scaffold → demonstrate → self-check. This supports beginner confidence while keeping the interface simple and consistent.