LearnWithKiriti

Insertion Sort

Easy GitHub ↗
đź’» Try it yourself first. Write your solution in Java, C++, Python or JavaScript and run it against hidden tests, right here. New: mock interview with Mr. Tock. Explain your approach out loud, he pushes you to improve it, then you code it. You get a scorecard at the end.
Play
On this page
  1. Revision notes
  2. Optimal: Make Room Then Insert

Revision notes

Insertion Sort

Video: “Insertion Sort: make room for one more book” on LearnWithKiriti (Kodee).

Sort an array by growing a sorted left part: insert each next number into its place among the numbers before it. Example: [7, 2, 8, 1, 5] -> [1, 2, 5, 7, 8]

Folder Approach Time Extra space
Optimal-MakeRoomThenInsert/ Make room, then insert: take the newBook, shift every bigger book one step right to make room, then drop newBook into the gap. One write per step. O(n²) worst, O(n) if almost sorted O(1)

Rebuild it from the name

Insertion: make room, then insert one more book. The books left of newBookSpot are already sorted on the shelf. Pick up the newBook, slide every bigger book one step right, and the empty gap moves left until the book on its left is not bigger. Drop newBook into the gap. Almost-sorted shelves need hardly any shifting, which is why insertion sort is O(n) there.

See Optimal-MakeRoomThenInsert/pseudocode.md. Every program runs Example 1 and prints the answer (the part under “Run it locally”); the solution itself is the same code as the practice panel’s Start menu on learnwithkiriti.com, where Shelf Bot can act it out.

optimal

Optimal: Make Room Then Insert

Insertion sort: make room, then insert

Take the newBook, shift every bigger book one step right to make room, then drop newBook into the gap. One write per step.

for newBookSpot from 1 to size - 1:
    newBook = nums[newBookSpot]
    gap = newBookSpot
    while gap > 0 and nums[gap - 1] > newBook:
        nums[gap] = nums[gap - 1]     // shift right
        gap = gap - 1
    nums[gap] = newBook

Dry run on Example 1:

Inserting 1 (newBookSpot = 3) into [2, 7, 8 | 1, 5]:

gap shift array
3 8 moves right [2, 7, 8, 8, 5]
2 7 moves right [2, 7, 7, 8, 5]
1 2 moves right [2, 2, 7, 8, 5]
0 stop, write newBook [1, 2, 7, 8, 5]

O(n²) worst case (reversed), O(n) best case (already sorted), great for almost-sorted data. O(1) extra space. Stable.

InsertionSortOptimal.java
class Solution {
    public void insertionSort(int[] nums) {
        // everything left of newBookSpot is already sorted
        for (int newBookSpot = 1; newBookSpot < nums.length; newBookSpot++) {
            int newBook = nums[newBookSpot];
            int gap = newBookSpot;
            // shift every bigger book one step right to make room
            while (gap > 0 && nums[gap - 1] > newBook) {
                nums[gap] = nums[gap - 1];
                gap--;
            }
            nums[gap] = newBook;
        }
    }
}