Insertion Sort: Solution and Explanation
Given an array of integers, sort it in ascending order using insertion sort. The algorithm grows a sorted prefix one element at a time, sliding each new element left until it sits in the correct spot.
Watch it run step by step
Try your own input and write the code →Intuition
Insertion sort is how most people sort a hand of playing cards. You hold the cards you have already arranged, pick up the next one, and slide it left past every card that is larger until it fits. The cards to the left of your hand are always sorted, and each new card makes that sorted group one longer.
In array terms, before processing index i, the prefix arr[0..i-1] is sorted. You copy arr[i] into a variable called key, which frees its slot. Then you walk a pointer j leftward from i - 1. Every element larger than key moves one position right into the free slot, which opens a new free slot one step further left. When you meet an element that is not larger than key (or run off the front of the array), the free slot is exactly where key belongs, so you drop it in at j + 1.
The amount of work depends on how disordered the input is. Each shift fixes exactly one inversion, meaning one pair of elements that were in the wrong relative order. A reverse sorted array has about n²/2 inversions and costs quadratic time, but an array that is already sorted has none, so the inner loop never runs and the whole sort is a single linear pass. That adaptiveness is why real-world libraries such as Timsort and introsort switch to insertion sort for small or nearly sorted chunks.
Approach: Shift and insert into a sorted prefix
- Loop
ifrom 1 tolen(arr) - 1. The single element at index 0 is a sorted prefix on its own. - Save
key = arr[i]so its slot can be overwritten by shifts. - Set
j = i - 1, the last index of the sorted prefix. - While
j >= 0andkey < arr[j], copyarr[j]intoarr[j + 1]and decrementj. - When the loop stops, write
keyintoarr[j + 1], which is the gap left by the last shift. - After the outer loop finishes, return
arr.
Step-by-step example
arr = [5, 2, 4, 1]
- i = 1, key = 2: 2 < 5, so shift 5 right to get [5, 5, 4, 1] and j becomes -1. Place key at index 0: [2, 5, 4, 1].
- i = 2, key = 4: 4 < 5, so shift 5 right to get [2, 5, 5, 1]. Next 4 < 2 is false, so place key at index 1: [2, 4, 5, 1].
- i = 3, key = 1: shift 5, then 4, then 2, giving [2, 2, 4, 5] with j = -1. Place key at index 0: [1, 2, 4, 5].
- The outer loop ends and the function returns [1, 2, 4, 5].
Code: Python, Java, C++
1class Solution:
2 def insertionSort(self, arr: List[int]) -> List[int]:
3 for i in range(1, len(arr)):
4 key = arr[i]
5 j = i - 1
6 while j >= 0 and key < arr[j]:
7 arr[j + 1] = arr[j]
8 j -= 1
9 arr[j + 1] = key
10 return arr1class Solution {
2 public int[] insertionSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 1; i < n; ++i) {
5 int key = arr[i];
6 int j = i - 1;
7
8 while (j >= 0 && arr[j] > key) {
9 arr[j + 1] = arr[j];
10 j = j - 1;
11 }
12 arr[j + 1] = key;
13 }
14 return arr;
15 }
16}1class Solution {
2public:
3 vector<int> insertionSort(vector<int>& arr) {
4 int n = arr.size();
5 for (int i = 1; i < n; i++) {
6 int key = arr[i];
7 int j = i - 1;
8 while (j >= 0 && arr[j] > key) {
9 arr[j + 1] = arr[j];
10 j = j - 1;
11 }
12 arr[j + 1] = key;
13 }
14 return arr;
15 }
16};Time and space complexity
O(n²)
In the worst case, a reverse sorted array, element i shifts past all i elements before it, so the total is 1 + 2 + up to n - 1, which is about n²/2 shifts. In the best case, an already sorted array, the inner condition fails immediately and the sort is O(n).
O(1)
The only extra storage is key and the loop indices. Elements are shifted inside the original array.
Other approaches
Binary insertion sort (time O(n²), space O(1))
Uses binary search to find where key belongs in the sorted prefix, cutting comparisons to O(n log n). Shifting elements still costs O(n²) in the worst case, so it helps only when comparisons are expensive.
Merge sort (time O(n log n), space O(n))
Divide and conquer sort that guarantees O(n log n) on every input. It needs a temporary buffer but is the right choice when the array is large or the order is random.
Common mistakes
- Checking
key < arr[j]beforej >= 0. The bounds check must come first, otherwise the loop readsarr[-1], which in Python silently wraps to the last element and in Java or C++ is out of bounds. - Writing
keytoarr[j]instead ofarr[j + 1]after the loop. When the loop stops,jpoints at the element that is not larger thankey, so the gap is one to the right. - Using
key <= arr[j]in the condition. That still sorts, but equal elements get shifted past each other and the sort is no longer stable. - Swapping neighbors on every step instead of shifting and doing one final write. It works, but it triples the number of assignments.
Frequently asked questions
What is the best case time complexity of insertion sort?
O(n). If the input is already sorted, each key is compared once with its left neighbor and stays where it is, so the inner loop never shifts anything.
Is insertion sort stable?
Yes. Because the inner loop only moves elements that are strictly greater than key, equal values never cross each other and keep their original order.
Why is insertion sort faster than bubble sort in practice?
Both are quadratic, but insertion sort shifts with a single write per step and stops as soon as the key is placed. Bubble sort swaps neighbors across the whole unsorted region on each pass, doing more writes and comparisons on average.
Why do standard libraries still use insertion sort?
For very small arrays its low overhead beats the bookkeeping of recursive algorithms. Hybrid sorts like Timsort and introsort hand off subarrays of roughly 16 to 64 elements to insertion sort for that reason.