Insertion sort

On this page 7

Insertion sort is a comparison-based sorting algorithm that builds the final sorted sequence one element at a time, taking each new element and inserting it into its correct position within the already sorted prefix. Among algorithms in programming, it is the standard example of an in-place, stable method with quadratic worst-case time but excellent performance on small or nearly sorted data.

Despite its simplicity, insertion sort is not merely a teaching exercise. Production sorting routines in major language libraries switch to insertion sort for short subarrays, typically below 16 to 32 elements, because its low overhead beats more sophisticated algorithms at that scale.

How insertion sort builds a sorted prefix

Insertion sort maintains a loop invariant: before processing position i, the elements at positions 0 through i minus 1 are sorted relative to each other. The algorithm takes the element at position i, called the key, and compares it with the elements to its left, shifting each larger element one position to the right until it finds the correct slot for the key.

The process resembles the way many card players arrange a hand. Each newly drawn card is slid leftward past higher cards until it sits in order. Formally, the procedure has three repeated steps:

  1. Store the key at position i in a temporary variable.
  2. Shift larger elements of the sorted prefix one position to the right.
  3. Write the key into the gap left behind and advance to position i plus 1.

Because the algorithm shifts elements instead of swapping them pairwise, each move costs a single write. The comparison uses a strict greater-than test, so equal elements never pass each other, which is what makes insertion sort stable: records with equal keys keep their original relative order.

Time and space complexity of insertion sort

The running time of insertion sort depends heavily on the initial order of the input. Its cost is proportional to the number of inversions, the pairs of elements that appear in the wrong order, plus the number of elements.

Input caseComparisonsElement movesTime complexity
Already sortedAbout nZero shiftsO(n)
Nearly sortedAbout n plus inversionsEqual to inversionsClose to O(n)
Random orderAbout n squared divided by 4About n squared divided by 4O(n squared)
Reverse sortedAbout n squared divided by 2About n squared divided by 2O(n squared)
Complexity of insertion sort by input case

The algorithm needs only O(1) auxiliary space, a single temporary variable for the key, so it sorts in place. It is also an online algorithm: it can sort a sequence as elements arrive, because each new element only needs to be inserted into the existing sorted part.

A frequent misconception is that binary insertion sort, which finds the insertion point with binary search, fixes the quadratic cost. It reduces comparisons to O(n log n), but the number of element shifts stays quadratic in the worst case, so the overall time complexity remains O(n squared) on arrays.

Insertion sort compared with other sorting algorithms

Insertion sort belongs to the family of elementary quadratic sorts, yet it behaves very differently from its neighbors. The table compares it with the sorting algorithms most often discussed alongside it.

AlgorithmBest caseWorst caseStableExtra space
Insertion sortO(n)O(n squared)YesO(1)
Bubble sortO(n) with early exitO(n squared)YesO(1)
Selection sortO(n squared)O(n squared)No in usual formO(1)
Merge sortO(n log n)O(n log n)YesO(n)
QuicksortO(n log n)O(n squared)No in usual formO(log n) stack
HeapsortO(n log n)O(n log n)NoO(1)
Insertion sort and related sorting algorithms

Against bubble sort, insertion sort performs roughly half the comparisons on random data and far fewer writes, so there is almost no practical reason to prefer bubble sort. Selection sort makes the fewest writes of the three, at most n minus 1 swaps, which matters only where writes are very expensive, but it gains nothing from presorted input.

Where insertion sort is used in practice

Insertion sort earns its place wherever inputs are small or almost sorted. Its tight inner loop, sequential memory access and lack of recursion give it very small constant factors, which dominate when n is small.

SituationRecommended choiceReason
Fewer than about 20 elementsInsertion sortLowest overhead at small sizes
Large data with few inversionsInsertion sortRuns in near-linear time
Base case inside a hybrid sortInsertion sortSpeeds up recursive algorithms
Large random dataMerge sort, quicksort or a library sortQuadratic cost becomes prohibitive
Strict worst-case guaranteesHeapsort or merge sortGuaranteed O(n log n)
When to choose insertion sort

Hybrid algorithms rely on this behavior. Timsort, used in Python and in Java for object arrays, applies binary insertion sort to build short sorted runs before merging them. Introsort, common in C++ standard library implementations, finishes small partitions with insertion sort. Embedded systems with tiny datasets and no dynamic memory also favor it because the code is short and predictable.

Common mistakes when implementing insertion sort

The algorithm is short, but small implementation errors break either correctness or stability. Most of them concern the boundaries of the inner loop.

  • Using greater-than-or-equal in the comparison moves equal elements past each other and destroys stability.
  • Forgetting the lower bound check lets the inner loop read before the start of the array when the key is the smallest value.
  • Swapping instead of shifting produces correct output but roughly triples the number of writes.
  • Applying it to large random data turns a fast routine into a bottleneck, since doubling n quadruples the running time.

A sentinel technique can remove the lower bound check: placing the minimum element at position 0 first guarantees that the inner loop always stops. This saves one comparison per step, a micro-optimization that some library implementations use for the small partitions they sort with insertion sort.

A plain-language summary

Insertion sort puts items in order the way many people sort a hand of playing cards. You pick up one card at a time and slide it left past any higher cards until it sits in the right spot. The cards already in your hand always stay in order.

This method is very quick when the list is short or already almost in order, because each new item only moves a little. When the list is long and completely mixed up, it becomes slow, since every new item may have to travel past many others. That is why computers use it for small jobs and switch to faster methods for big ones.

An example from practice

A developer maintains a live leaderboard for an online game with 50,000 ranked players. Scores change constantly, but between refreshes each player usually moves only a few positions. Re-sorting the entire list with a general-purpose sort every second costs noticeable CPU time on the server.

Because the list is already nearly sorted, the developer applies insertion sort to the previous ranking after updating the changed scores. The number of inversions per refresh is typically a few thousand, so the pass finishes in near-linear time, and the sort is stable, so tied players keep their earlier order. Measured refresh time drops from about 9 ms to under 1 ms, while a fallback to the library sort handles rare events such as a mass score reset.