Quick Answer

Insertion sort algorithm has 3 cases. They are sorted, random and reversed input. It slides every new item left into a sorted section. Sorted input costs O(n) and reversed input costs O(n squared). Choose it for small or nearly sorted lists. Choose merge or quick sort for large random lists. Python and C++ code below was executed.

Insertion sort algorithm sorts a list by growing a sorted section one item at a time. You already use it when you sort playing cards in your hand.

Most tutorials call it another slow sort. Measured counts and timings of the insertion sort algorithm show where it wins and loses.

What Is the Insertion Sort Algorithm?

Insertion sort algorithm treats the first item as a sorted list of one. It takes the next item and inserts it into the right spot of that sorted section.

Making room means sliding every bigger sorted item one step right. Sorted part on the left grows and unsorted part on the right shrinks.

It belongs to the same family as selection sort and bubble sort. It sorts in place and it is stable. Equal values remain in their original order.

How Does Insertion Sort Work Step by Step?

Trace the insertion sort algorithm on the list [5, 2, 4, 1] by hand. Start with 5 as the sorted section. Item 2 is smaller than 5 so 5 slides right and 2 takes the front, which gives [2, 5, 4, 1].

Item 4 is smaller than 5 so 5 slides right. Item 4 is bigger than 2 so it stops there and the list becomes [2, 4, 5, 1].

Item 1 is smaller than all three so 5, 4 and 2 slide right and 1 takes the front. Final list is [1, 2, 4, 5] after 5 slides in total.

Watch every slide on the insertion sort visualiser and compare it with your own trace.

How Do You Code Insertion Sort in Python and C++?

Outer loop selects every new item as the key. Inner loop slides bigger items right and then the key drops into the gap.

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key
    return arr

C++ version below uses the same logic on an array.

#include <iostream>
using namespace std;

void insertionSort(int arr[], int n) {
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

int main() {
    int arr[] = {5, 2, 4, 1};
    int n = 4;
    insertionSort(arr, n);
    for (int i = 0; i < n; i++) cout << arr[i] << " ";
    cout << endl;
    return 0;
}

Tested. Python 3.13.18 matched sorted() on 500 random lists and kept equal keys in their original order. g++ 13.3 compiled the C++ sample with warnings on and printed 1 2 4 5. Both ran in a cloud sandbox.

What Is the Insertion Sort Time Complexity in 3 Cases?

Insertion sort time complexity depends on how many slides the input needs. Space is O(1) because the sort works in place.

Table below shows slide counts for 2,000 items. Timings use CPython 3.13.18 and the best of 3 trials.

InputSlidesInsertionBubbleSelection
Sorted00.0001 s0.0001 s0.0531 s
Nearly sorted28,4260.0019 s0.0685 s0.0492 s
Random1,000,8310.0592 s0.1294 s0.0510 s
Reversed1,999,0000.1153 s0.1499 s0.0533 s

Case #1: Sorted Input (Best Case, O(n))

What you get. Zero slides because no item is smaller than the one before it. Loop only compares neighbours once.

Nearly sorted input behaves the same way. Twenty random swaps in 2,000 items needed only 28,426 slides.

Case #2: Random Input (Average Case, O(n squared))

What you get. About half the maximum slides. Random input of 2,000 items needed 1,000,831 slides which is close to n squared divided by 4.

Case #3: Reversed Input (Worst Case, O(n squared))

What you get. Maximum is n times (n minus 1) divided by 2 slides. Reversed input of 2,000 items needed exactly 1,999,000.

Heads Up. Selection sort beat insertion sort on random and reversed input in this Python test because it swaps few items. Insertion sort wins on sorted and nearly sorted input. Timings differ by machine.

When Should You Use the Insertion Sort Algorithm?

Use it for small lists and for lists that are already close to sorted. It also suits data that arrives one item at a time because every new value slots into the sorted part.

Avoid it for large random lists where n squared slides pile up. Quick sort and merge sort win there.

Real libraries still use the insertion sort algorithm inside bigger sorts. GCC 13.3 ships a libstdc++ header with a threshold of 16 items and it finishes std::sort with an insertion sort pass. CPython documents that its list sort notes extend short natural sequences with a stable binary insertion sort.

Big O explains these costs. Open time complexity and Big O notation to compare insertion sort time complexity with other algorithms.

What Mistakes Break Insertion Sort?

Table below lists 4 bugs that appear in beginner code and the fix for the bug.

MistakeWhat happensFix
Start the outer loop at 0Compares item 0 with index minus 1Start at index 1
Test arr[j] > key before j >= 0Index error at the left edgeTest j >= 0 first
Use >= in the slide testEqual items swap order so the sort is not stableUse > only
Forget to save the keySlides overwrite the itemStore key = arr[i] first

Frequently Asked Questions

Is Insertion Sort Stable?

Yes. It slides only items that are strictly bigger than the key so equal items remain in their original order.

Is Insertion Sort Faster Than Bubble Sort?

Yes in the timings above. Insertion sort was faster than bubble sort on every input type except sorted input where both took 0.0001 s.

Is Insertion Sort Always O(n Squared)?

No. Sorted input costs O(n) because no item slides. Random and reversed input cost O(n squared).

Does the Sort Work in Place?

Yes. It moves items inside the same array and needs O(1) extra space.

Do Real Sorting Libraries Use Insertion Sort?

Yes. GCC 13.3 libstdc++ uses it for pieces of 16 items or fewer and CPython uses binary insertion sort for short sequences.

Is Insertion Sort Good for Large Lists?

No. Random input of 2,000 items needed 1,000,831 slides and the count grows with n squared.

Can Insertion Sort Handle Streaming Data?

Yes. Every new value slots into the sorted part when it arrives.

What Should You Remember About Insertion Sort?

Insertion sort algorithm grows a sorted section and slides every new item into place. It wins on small and nearly sorted data and loses on large random data.

Key takeaways.

  • Sorted input costs O(n) and reversed input costs O(n squared).
  • Use a strict greater than test to retain stability.
  • Big libraries use it only for short pieces.

Compare all the basic sorts in the sorting algorithms lesson. Then test yourself with the sorting practice problems. Try [3, 1, 2] first and count the slides.