Insertion Sort: Step-by-Step Example, Code and Time Complexity

Insertion Sort: Step-by-Step Example, Code and Time Complexity

Short answer: insertion sort is a simple sorting algorithm that builds the sorted list one item at a time. It takes the next item, shifts every bigger item in the sorted part one place to the right, and drops the item into the gap. It runs in O(n) time on sorted input and O(n²) on average and in the worst case, with O(1) extra memory.

Below you will find a worked example traced pass by pass, code in C, Python and Java, exact comparison and shift counts, and where real libraries still use insertion sort. Every output shown was produced by running the code.

What is insertion sort?

Think of how you sort playing cards in your hand. You pick up one card at a time and slide it left past every bigger card. The cards in your hand stay in order.

Insertion sort does the same to an array. It treats the array as two parts:

  • the sorted part on the left, which starts as just the first item;
  • the unsorted part on the right, which is everything else.

Each round, called a pass, takes the first unsorted item, called the key. It compares the key with the sorted items from right to left. Every item bigger than the key is shifted one place to the right. When the search meets an item that is smaller or equal, or runs out of items, the key drops into the gap.

After pass i, the first i + 1 items are sorted among themselves. They are not yet in their final places, because a smaller item may still arrive later. That is the main difference from selection sort, whose sorted part is already final.

Insertion sort algorithm, step by step

  1. Treat the first item as a sorted part of length 1.
  2. Take the next item as the key and remember it.
  3. Compare the key with the sorted items, starting from the right end.
  4. While the item you compare is bigger than the key, shift it one place right.
  5. Stop at the first item that is smaller than or equal to the key, or at the start of the array. Put the key in the gap.
  6. Repeat from step 2 until the unsorted part is empty.

Here is the same thing as pseudocode, with indexes starting at 0:

for i from 1 to n - 1:
    key = a[i]
    j = i - 1
    while j >= 0 and a[j] > key:
        a[j + 1] = a[j]        # shift right
        j = j - 1
    a[j + 1] = key             # insert

Step 5 is the important one. The search stops at the first item that is not bigger than the key, instead of scanning the whole sorted part. That early stop makes insertion sort fast on sorted input.

Use > in the loop condition, not >=. With >=, equal items swap places and the sort is no longer stable.

Insertion sort example, pass by pass

Let's sort [4, 3, 2, 10, 12, 1, 5, 6]. This program runs insertion sort and prints every pass. The | marks where the sorted part ends. "comparisons" counts how many times the key was compared with an item.

def show(a, sorted_len):
    left = ", ".join(str(x) for x in a[:sorted_len])
    right = ", ".join(str(x) for x in a[sorted_len:])
    return f"[{left} | {right}]" if right else f"[{left}]"


def insertion_sort_trace(items):
    a = list(items)
    total_comparisons = total_shifts = 0
    print("pass  key  comparisons  shifted right    array after the pass")
    print(f"   -    -            -  -                {show(a, 1)}")
    for i in range(1, len(a)):
        key = a[i]                      # the item to insert this pass
        j = i - 1
        comparisons, shifted = 0, []
        while j >= 0:
            comparisons += 1
            if a[j] <= key:             # found the spot: stop
                break
            a[j + 1] = a[j]             # shift the bigger item one place right
            shifted.append(a[j])
            j -= 1
        a[j + 1] = key                  # drop the key into the gap
        total_comparisons += comparisons
        total_shifts += len(shifted)
        moved = ", ".join(map(str, shifted)) or "none"
        print(f"{i:>4} {key:>4} {comparisons:>12}  {moved:<16} {show(a, i + 1)}")
    print(f"total: {total_comparisons} comparisons, {total_shifts} shifts")


insertion_sort_trace([4, 3, 2, 10, 12, 1, 5, 6])
pass  key  comparisons  shifted right    array after the pass
   -    -            -  -                [4 | 3, 2, 10, 12, 1, 5, 6]
   1    3            1  4                [3, 4 | 2, 10, 12, 1, 5, 6]
   2    2            2  4, 3             [2, 3, 4 | 10, 12, 1, 5, 6]
   3   10            1  none             [2, 3, 4, 10 | 12, 1, 5, 6]
   4   12            1  none             [2, 3, 4, 10, 12 | 1, 5, 6]
   5    1            5  12, 10, 4, 3, 2  [1, 2, 3, 4, 10, 12 | 5, 6]
   6    5            3  12, 10           [1, 2, 3, 4, 5, 10, 12 | 6]
   7    6            3  12, 10           [1, 2, 3, 4, 5, 6, 10, 12]
total: 16 comparisons, 12 shifts
  • Passes 3 and 4: 10 and 12 are already bigger than everything before them. One comparison each, no shifts.
  • Pass 5: 1 is smaller than all five sorted items, so all five shift right. There is no extra comparison to stop, because the search ran off the start of the array.
  • Passes 6 and 7: 5 and 6 each move past 12 and 10, then stop at a smaller item. The stop costs one extra comparison.

In total the 8 items needed 16 comparisons and 12 shifts. Here are the same passes as a picture:

Insertion sort example on 4, 3, 2, 10, 12, 1, 5, 6: each row shows the array before one pass, with the key in green and the bigger items it moves past in red, ending with 1, 2, 3, 4, 5, 6, 10, 12

Insertion sort in C

The function sorts the array in place. Note the order of the two tests in the while loop. C evaluates && from left to right and stops at the first false test, so a[-1] is never read.

#include <stdio.h>

/* Sort a[0..n-1] in ascending order, in place. */
void insertion_sort(int a[], int n) {
    for (int i = 1; i < n; i++) {
        int key = a[i];             /* the item to insert */
        int j = i - 1;
        /* Check j >= 0 first, so a[-1] is never read. */
        while (j >= 0 && a[j] > key) {
            a[j + 1] = a[j];        /* shift the bigger item one place right */
            j--;
        }
        a[j + 1] = key;             /* drop the key into the gap */
    }
}

void print_array(const char *label, const int a[], int n) {
    printf("%s", label);
    for (int i = 0; i < n; i++) printf(i ? " %d" : "%d", a[i]);
    printf("\n");
}

int main(void) {
    int a[] = {4, 3, 2, 10, 12, 1, 5, 6};
    int b[] = {45, -1, 16, 6, 16, 0};
    int n = sizeof a / sizeof a[0];
    int m = sizeof b / sizeof b[0];

    print_array("before: ", a, n);
    insertion_sort(a, n);
    print_array("after:  ", a, n);

    print_array("before: ", b, m);
    insertion_sort(b, m);
    print_array("after:  ", b, m);
    return 0;
}
before: 4 3 2 10 12 1 5 6
after:  1 2 3 4 5 6 10 12
before: 45 -1 16 6 16 0
after:  -1 0 6 16 16 45

The second array has a negative number and a repeated value (16). Neither needs special handling.

Insertion sort in Python

def insertion_sort(arr):
    """Sort arr in place in ascending order and return it."""
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:  # shift bigger items one place right
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr


print(insertion_sort([4, 3, 2, 10, 12, 1, 5, 6]))
print(insertion_sort([45, -1, 16, 6, 16, 0]))
print(insertion_sort(["mango", "apple", "kiwi", "banana"]))
print(insertion_sort([]), insertion_sort([7]))
[1, 2, 3, 4, 5, 6, 10, 12]
[-1, 0, 6, 16, 16, 45]
['apple', 'banana', 'kiwi', 'mango']
[] [7]

It works for any items that can be compared with >, such as strings. Empty and one-item lists come back unchanged. In real Python code, call sorted() or list.sort() instead.

Insertion sort in Java

import java.util.Arrays;

public class InsertionSort {
    // Sort a in ascending order, in place.
    static void insertionSort(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int key = a[i];
            int j = i - 1;
            while (j >= 0 && a[j] > key) {   // shift bigger items one place right
                a[j + 1] = a[j];
                j--;
            }
            a[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] a = {4, 3, 2, 10, 12, 1, 5, 6};
        insertionSort(a);
        System.out.println(Arrays.toString(a));

        int[] b = {45, -1, 16, 6, 16, 0};
        insertionSort(b);
        System.out.println(Arrays.toString(b));
    }
}
[1, 2, 3, 4, 5, 6, 10, 12]
[-1, 0, 6, 16, 16, 45]

Save it as InsertionSort.java, then run javac InsertionSort.java and java InsertionSort.

Counting comparisons and shifts

To predict the cost of insertion sort, you need one idea: the inversion. An inversion is a pair of items in the wrong order, where an earlier item is bigger than a later one. [4, 3, 2] has 3 inversions: (4, 3), (4, 2) and (3, 2).

Each shift moves a bigger item one place past a smaller one. That fixes exactly one inversion and changes nothing else. So the number of shifts always equals the number of inversions in the input. The example above had 12 inversions, so it needed 12 shifts.

This program counts comparisons and shifts on four kinds of input. It also counts inversions by checking every pair, and asserts that the two numbers match.

import random


def insertion_sort_counts(items):
    """Insertion sort that counts key comparisons and shifts."""
    a = list(items)
    comparisons = shifts = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0:
            comparisons += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            shifts += 1
            j -= 1
        a[j + 1] = key
    assert a == sorted(items)
    return comparisons, shifts


def inversions(items):
    """Brute force: count pairs i < j with items[i] > items[j]."""
    n = len(items)
    return sum(1 for i in range(n) for j in range(i + 1, n) if items[i] > items[j])


rng = random.Random(7)
print("input            n  comparisons  shifts  inversions")
for n in [10, 100, 1000]:
    nearly = list(range(n))
    for _ in range(n // 10):                 # swap a few random neighbours
        k = rng.randrange(n - 1)
        nearly[k], nearly[k + 1] = nearly[k + 1], nearly[k]
    inputs = {
        "sorted": list(range(n)),
        "nearly sorted": nearly,
        "random": rng.sample(range(n), n),
        "reversed": list(range(n, 0, -1)),
    }
    for name, data in inputs.items():
        c, s = insertion_sort_counts(data)
        inv = inversions(data)
        assert s == inv                       # every shift fixes one inversion
        print(f"{name:<13} {n:>4} {c:>12,} {s:>7,} {inv:>11,}")
    print(f"  for n = {n:,}: n - 1 = {n - 1:,} and n(n - 1)/2 = {n * (n - 1) // 2:,}")
input            n  comparisons  shifts  inversions
sorted          10            9       0           0
nearly sorted   10           10       1           1
random          10           29      21          21
reversed        10           45      45          45
  for n = 10: n - 1 = 9 and n(n - 1)/2 = 45
sorted         100           99       0           0
nearly sorted  100          107       8           8
random         100        2,731   2,640       2,640
reversed       100        4,950   4,950       4,950
  for n = 100: n - 1 = 99 and n(n - 1)/2 = 4,950
sorted        1000          999       0           0
nearly sorted 1000        1,092      94          94
random        1000      249,995 249,003     249,003
reversed      1000      499,500 499,500     499,500
  for n = 1,000: n - 1 = 999 and n(n - 1)/2 = 499,500

What the counts show:

  • Sorted input is the best case: n − 1 comparisons and 0 shifts (9, 99 and 999). Each key is compared once with its left neighbour and stays put.
  • Reversed input is the worst case: n(n − 1)/2 comparisons and shifts (45, 4,950 and 499,500). Every key travels to the front.
  • Random input lands near the middle. At n = 1,000 it needed 249,003 shifts, about half of the worst case's 499,500.
  • Nearly sorted input is cheap. With n/10 random neighbour swaps, n = 1,000 needed only 94 shifts.

Comparisons stay close to shifts: one per shift, plus one to stop, unless the key reached the front.

Insertion sort time complexity

CaseInput that causes itComparisonsTime
BestAlready sortedn − 1Θ(n)
AverageRandom orderabout n²/4Θ(n²)
WorstReverse sortedn(n − 1)/2Θ(n²)

Θ (Big Theta) means a tight bound: the cost grows in proportion to that function, up to a constant factor. Θ(n) means doubling n doubles the work. Θ(n²) means doubling n makes it about four times bigger. If the notation is new, read what time complexity is and how to calculate it.

Why the average case is n²/4

Take any two positions in a random ordering. The bigger value is just as likely to come first as second. So each of the n(n − 1)/2 pairs is an inversion with probability 1/2. The expected number of inversions, and so of shifts, is n(n − 1)/4.

This program checks that prediction. It sorts 1,000 random orderings of each size and averages the counts. Because it is an average over trials, it lands close to n(n − 1)/4 but not exactly on it.

import random


def shifts_and_comparisons(items):
    a = list(items)
    comparisons = shifts = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0:
            comparisons += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            shifts += 1
            j -= 1
        a[j + 1] = key
    return comparisons, shifts


rng = random.Random(2026)
trials = 1000
print("   n  avg shifts  n(n-1)/4  avg comparisons")
for n in [10, 50, 100]:
    total_c = total_s = 0
    for _ in range(trials):
        c, s = shifts_and_comparisons(rng.sample(range(n), n))  # a random permutation
        total_c += c
        total_s += s
    print(f"{n:>4} {total_s / trials:>11,.1f} {n * (n - 1) / 4:>9,.1f} {total_c / trials:>16,.1f}")
   n  avg shifts  n(n-1)/4  avg comparisons
  10        22.4      22.5             29.5
  50       608.5     612.5            654.0
 100     2,476.2   2,475.0          2,571.1

For n = 100 the average was 2,476.2 shifts against a predicted 2,475.0. Half of the worst case is still quadratic, so the average case is Θ(n²).

Space complexity

Insertion sort needs one variable for the key and two indexes, whatever the size of the array. That is O(1) auxiliary space: a constant amount of extra memory, not zero memory. A recursive version needs a stack frame per item, which is O(n) extra space, so the loop version is the one to use.

Stable, in place, online, adaptive: what each term means

Interviewers like these four words because insertion sort has all four properties.

  • In place: it sorts inside the array it was given, using O(1) extra memory.
  • Stable: items with equal keys keep their original order.
  • Adaptive: it runs faster when the input is already partly sorted. Its cost grows with n plus the number of inversions, as the nearly sorted rows above showed.
  • Online: it can sort items as they arrive, without seeing the whole list first.

Stability in action

Here, students are sorted by marks. Asha and Meera both have 82, and Asha comes first in the input. The only difference between the two runs is > versus >= in the shift test.

import operator


def insertion_sort_by(records, key, bigger):
    a = list(records)
    for i in range(1, len(a)):
        item = a[i]
        j = i - 1
        while j >= 0 and bigger(key(a[j]), key(item)):
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = item
    return a


students = [("Asha", 82), ("Ravi", 91), ("Meera", 82), ("Kiran", 75)]
marks = lambda s: s[1]
print("with > :", insertion_sort_by(students, marks, operator.gt))   # correct
print("with >=:", insertion_sort_by(students, marks, operator.ge))   # the bug
with > : [('Kiran', 75), ('Asha', 82), ('Meera', 82), ('Ravi', 91)]
with >=: [('Kiran', 75), ('Meera', 82), ('Asha', 82), ('Ravi', 91)]

With >, Asha stays ahead of Meera. With >=, Meera's key shifts past the equal 82, and she jumps ahead. Stability matters when you sort by one key and then another, for example by name and then by marks.

Online sorting

Python's bisect.insort does one insertion step: it finds the spot with binary search and inserts the new item there. Calling it as each item arrives keeps a list sorted at all times.

import bisect

scores = []
for new_score in [72, 95, 64, 88, 95, 70]:      # scores arrive one at a time
    bisect.insort(scores, new_score)           # one insertion step per arrival
    print(f"got {new_score}: {scores}")
got 72: [72]
got 95: [72, 95]
got 64: [64, 72, 95]
got 88: [64, 72, 88, 95]
got 95: [64, 72, 88, 95, 95]
got 70: [64, 70, 72, 88, 95, 95]

The Python documentation adds a warning: "the O(log n) search is dominated by the slow O(n) insertion step." The next section shows the same effect with numbers.

Binary insertion sort

The search for the gap happens inside the sorted part. So you can use binary search there, instead of walking left one item at a time. That variant is called binary insertion sort. Binary search halves the range at each step, so pass i needs at most ⌈log₂(i + 1)⌉ comparisons.

This program runs both versions on the same inputs of 1,000 items and counts their comparisons and shifts.

import random


def linear_insertion_sort(items):
    a = list(items)
    comparisons = shifts = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0:
            comparisons += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            shifts += 1
            j -= 1
        a[j + 1] = key
    return a, comparisons, shifts


def binary_insertion_sort(items):
    a = list(items)
    comparisons = shifts = 0
    for i in range(1, len(a)):
        key = a[i]
        lo, hi = 0, i                   # search the sorted part a[0:i]
        while lo < hi:                  # find the first item bigger than key
            mid = (lo + hi) // 2
            comparisons += 1
            if key < a[mid]:
                hi = mid
            else:
                lo = mid + 1            # equal keys go right: stays stable
        for j in range(i, lo, -1):      # the shifting is still one by one
            a[j] = a[j - 1]
            shifts += 1
        a[lo] = key
    return a, comparisons, shifts


n = 1000
rng = random.Random(11)
inputs = {"sorted": list(range(n)), "random": rng.sample(range(n), n),
          "reversed": list(range(n, 0, -1))}
print(f"n = {n}           comparisons            shifts")
print("input        linear    binary     linear    binary")
for name, data in inputs.items():
    a1, c1, s1 = linear_insertion_sort(data)
    a2, c2, s2 = binary_insertion_sort(data)
    assert a1 == a2 == sorted(data)
    print(f"{name:<9} {c1:>9,} {c2:>9,} {s1:>10,} {s2:>9,}")
n = 1000           comparisons            shifts
input        linear    binary     linear    binary
sorted          999     7,987          0         0
random      249,028     8,588    248,038   248,038
reversed    499,500     8,977    499,500   499,500
  • Comparisons drop to O(n log n). On random input they fell from 249,028 to 8,588. On reversed input they fell from 499,500 to 8,977, which is exactly the sum of ⌈log₂(i + 1)⌉ over all 999 passes.
  • Shifts do not change at all. Finding the gap faster does not make room in it. Items still move one slot at a time, so the running time stays O(n²).
  • On sorted input, binary insertion sort is worse. It makes 7,987 comparisons where plain insertion sort makes 999, because it runs a full binary search even when the key is already in place.

So when is it worth it? When comparing two items costs far more than moving one. CPython's design notes say that in Python, "comparisons are extraordinarily expensive compared to moving data", because moving an object only copies a pointer (listsort.txt).

Where insertion sort is used in real libraries

Insertion sort is a poor choice for big arrays. For a few dozen items, though, its short loop has very little overhead, so production sorts hand small pieces to it. Each point below comes from the library's own source code, checked on 19 November 2026.

  • Python (CPython). list.sort() and sorted() use a merge sort that looks for runs of items already in order. A short run is extended to a minimum length, called minrun, "via a stable binary insertion sort". For longer lists minrun is between 32 and 64. A list shorter than 64 items is handled by binary insertion sort alone, with no merging (listsort.txt; MAX_MINRUN 64 in listobject.c).
  • JavaScript (V8, the engine in Chrome and Node.js). V8 replaced its quicksort with TimSort in V8 v7.0 and Chrome 70 (V8 blog, 28 September 2018). The current source sorts arrays of fewer than 16 elements with binary insertion sort, and uses the same routine to extend short runs (array-sort.tq, js-array.h). That source now calls its merge sort PowerSort.
  • C++ (GCC's libstdc++). std::sort is an introsort, a quicksort with a heap sort fallback. Its partition loop stops splitting a range once it has 16 or fewer items (_S_threshold = 16). Then __final_insertion_sort runs insertion sort over the whole array (stl_algo.h).
  • Java. Arrays.sort(int[]) uses a Dual-Pivot Quicksort (Java 21 docs). In JDK 17, JDK 21 and the current OpenJDK source, the leftmost part goes to insertion sort when it has fewer than 44 elements (MAX_INSERTION_SORT_SIZE = 44). Other small parts get a "mixed insertion sort", tuned by MAX_MIXED_INSERTION_SORT_SIZE = 65. JDK 8 and JDK 11 used one threshold of 47 (INSERTION_SORT_THRESHOLD) (DualPivotQuicksort.java).

The cut-offs differ (16, 44, 47, 64) because each team tuned them for its own language and data.

Insertion sort vs bubble sort vs selection sort

This program runs all three simple sorts on the same 100 items. It counts comparisons and writes, the times an array slot is overwritten (a swap is two writes). The bubble sort stops early after a pass with no swaps.

import random


def insertion_sort(a):
    comparisons = writes = 0
    for i in range(1, len(a)):
        key = a[i]
        j = i - 1
        while j >= 0:
            comparisons += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]             # one write per shift
            writes += 1
            j -= 1
        if j + 1 != i:                  # write the key only if it moved
            a[j + 1] = key
            writes += 1
    return comparisons, writes


def bubble_sort(a):                     # with the early exit
    comparisons = writes = 0
    n = len(a)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            comparisons += 1
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                writes += 2             # a swap writes two slots
                swapped = True
        if not swapped:
            break
    return comparisons, writes


def selection_sort(a):
    comparisons = writes = 0
    n = len(a)
    for i in range(n - 1):
        smallest = i
        for j in range(i + 1, n):
            comparisons += 1
            if a[j] < a[smallest]:
                smallest = j
        if smallest != i:
            a[i], a[smallest] = a[smallest], a[i]
            writes += 2
    return comparisons, writes


n = 100
rng = random.Random(5)
inputs = {"sorted": list(range(n)), "random": rng.sample(range(n), n),
          "reversed": list(range(n, 0, -1))}
print(f"{'n = 100':<10}{'insertion sort':>18}{'bubble sort':>18}{'selection sort':>18}")
print(f"{'input':<10}" + f"{'compares':>10}{'writes':>8}" * 3)
for name, data in inputs.items():
    row = f"{name:<10}"
    for sort in (insertion_sort, bubble_sort, selection_sort):
        a = list(data)
        c, w = sort(a)
        assert a == sorted(data)
        row += f"{c:>10,}{w:>8,}"
    print(row)
n = 100       insertion sort       bubble sort    selection sort
input       compares  writes  compares  writes  compares  writes
sorted            99       0        99       0     4,950       0
random         2,563   2,564     4,947   4,936     4,950     188
reversed       4,950   5,049     4,950   9,900     4,950     100

The same results as a summary, with the n = 100 counts in brackets:

Insertion sortBubble sort (early exit)Selection sort
Comparisons, best casen − 1 (99)n − 1 (99)n(n − 1)/2 (4,950)
Comparisons, worst casen(n − 1)/2 (4,950)n(n − 1)/2 (4,950)n(n − 1)/2 (4,950)
Writes, best case000
Writes, worst casen(n − 1)/2 + n − 1 (5,049)n(n − 1) (9,900)at most 2(n − 1) (100 on reversed input)
Time: best / average / worstΘ(n) / Θ(n²) / Θ(n²)Θ(n) / Θ(n²) / Θ(n²)Θ(n²) in every case
Stable?YesYesNo
Adaptive?YesOnly through the early exitNo
Online?YesNoNo
  • On random input, insertion sort made about half the comparisons of the other two: 2,563 against 4,947 and 4,950.
  • Insertion sort and bubble sort fix the same inversions, but at different prices. A shift is one write and a swap is two. On reversed input that is 5,049 writes against 9,900.
  • Selection sort makes the fewest writes, 188 on random input, but always 4,950 comparisons. Choose it only when writes cost much more than comparisons.

When to use insertion sort

Use it for small arrays, nearly sorted data and items that arrive one at a time. Avoid it for large arrays in random order: at n = 1,000, random input already needed 249,003 shifts. For big inputs, use merge sort, quick sort or your language's built-in sort.

Common interview questions

  1. How many shifts does insertion sort make? Exactly the number of inversions in the input: 0 when sorted, n(n − 1)/2 when reversed.
  2. Does binary search make insertion sort O(n log n)? No. Comparisons drop to O(n log n), but shifts stay O(n²).
  3. Can you write insertion sort recursively? Yes: sort the first n − 1 items, then insert the last one. It uses O(n) stack space, so the loop is better.
  4. What about a linked list? Inserting a node is O(1), but finding the spot still means walking the list. The worst case stays O(n²).

FAQ

What is insertion sort in simple words?

Insertion sort sorts a list the way you sort playing cards in your hand. It takes one item at a time from the unsorted part. It shifts every bigger item in the sorted part one place right, then drops the item into the gap. After the last item is placed, the whole list is sorted.

What is the time complexity of insertion sort?

The best case is Θ(n), for input that is already sorted: n − 1 comparisons and no shifts. The average and worst cases are Θ(n²). Reverse-sorted input is the worst case, with n(n − 1)/2 comparisons and shifts. Random input needs about n²/4 shifts on average. Extra space is O(1) in every case.

Is insertion sort stable?

Yes, as long as the shift test uses a strict greater-than (>). An item then moves only past items whose key is bigger, never past an equal one. So equal items keep their original order. If you write >= instead, equal items swap places and the sort is no longer stable.

Why is insertion sort better than bubble sort?

Both make n − 1 comparisons on sorted input and n(n − 1)/2 in the worst case. But on random input insertion sort makes about half as many comparisons. It also moves each item with single writes instead of swaps. For 100 reversed items, that was 5,049 writes against bubble sort's 9,900.

What is the difference between insertion sort and selection sort?

Insertion sort takes the next item and inserts it into the sorted part, so the sorted part is not final until the end. Selection sort finds the smallest remaining item and swaps it into place, so its sorted part is final. Insertion sort is stable and adaptive. Selection sort is neither, but it makes fewer writes.

When should I use insertion sort?

Use it for small arrays of a few dozen items, for data that is already nearly sorted, and for items that arrive one at a time. Real libraries use it this way inside their main sorts. Avoid it for large random arrays, where its Θ(n²) cost is far slower than merge sort or quick sort.

Keep going

See how insertion sort compares with other algorithms in our sorting algorithms guide. Then read what time complexity is and how to calculate it for the notation used in this post.

If you want to build these skills on real backend and full-stack projects, with mentors reviewing your code, look at Crio's Software Development Fellowship Program.

Harshita Bansal

Written by Harshita Bansal

It's only words, and words are all I have.
You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.