Core · Module 8 · Lesson 1 of 5
Insertion and selection sort
The two simplest sorts both take O(n²) steps on scrambled data, but they behave very differently: insertion sort is fast on nearly sorted input and is used inside every major library sort.
Pro — members onlyAbout 13 minutes
By the end you can
- Trace insertion sort and selection sort, and state each one's loop invariant
- Count their comparisons and moves in the best and worst cases, using inversions
- Explain why library sorts still use insertion sort on small pieces
Builds on Best, average and worst case.
01 · A question first
Insertion sort is O(n²). Python's sort, Java's object sort and C++'s std::sort all run it internally on small pieces of the array. Why would a modern library deliberately include a quadratic algorithm?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Why study slow sorts
- Insertion sort
- Counting with inversions
- Binary insertion sort
- Selection sort
- Why libraries use insertion sort
- Pseudocode & Multi-Language Implementations (C++, Java, Python)
- Complexity Derivation, Edge Cases & Common Mistakes
03 · Practice
Something wrong with this lesson? Report a problem