# Insertion Sort

> Take each item in turn. Slide it back to its right place.

**Field:** Software Development  
**Category:** Algorithms & Data Structures  
**Also known as:** Insertion Sorting, Card Sort

## Think of it like

It is like sorting cards in your hand. You pick up one card at a time and slide it into place.

## Definition

Insertion sort builds a sorted part one item at a time. It takes the next item and slides it back until it sits in the right spot. On a list that is already nearly sorted, it is very fast. On a big jumbled list it is slow, about n squared steps. Fast sorts often switch to it for very small pieces.

## Example

A list of 20 scores is in order except for one new score at the end. Insertion sort fixes it in a few steps.

## Example code

```python
def insertion_sort(a):
    for i in range(1, len(a)):
        x, j = a[i], i - 1
        while j >= 0 and a[j] > x:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = x
    return a
```

Each item moves back past the bigger ones, then drops into its gap.

## Why it matters

It is simple and quick on small or nearly sorted lists. Real sorting code uses it for that job.

## Common mistake

Using it on a large, random list. Merge sort or quicksort will be far faster there.

## Three principles

- **Grows a sorted part.** One item joins it each step.
- **Great when nearly sorted.** Few moves are needed.
- **Slow on big messes.** About n squared steps.

## Related terms

- [Sorting Algorithm](https://learn.benibix.com/term/development/sorting-algorithm)
- [Selection Sort](https://learn.benibix.com/term/development/selection-sort)
- [Bubble Sort](https://learn.benibix.com/term/development/bubble-sort)
- [Merge Sort](https://learn.benibix.com/term/development/merge-sort)
- [Best, Worst and Average Case](https://learn.benibix.com/term/development/best-worst-average-case)

## Told apart from

- [Insertion Sort vs Selection Sort](https://learn.benibix.com/compare/insertion-sort-vs-selection-sort): Insertion sort slides each item back into place. It is quick when the list is nearly in order. Selection sort looks for the smallest item on each pass. It is always slow.

![Two panels sorting the cards 5, 2, 4, 1. Insertion sort: the left part grows sorted, and the next card slides back into its place among them. Selection sort: the smallest card left, 1, is found and swapped to the front, then the next smallest, and so on.](https://learn.benibix.com/diagrams/dev7-simple-sorts.svg)

---

Source: https://learn.benibix.com/term/development/insertion-sort
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
