Insertion Sorting
Pattern: Basic sorts
Sort like a hand of cards. Take the next element and slide it left past every bigger element into its place.
The problem
You are given an array of between 1 and 1500 whole numbers. Sort it in increasing order using insertion sort, and return
it. For example, [4, 3, 1, 2] becomes [1, 2, 3, 4].
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name insertionSort and the limits are this guide's own.
Think first
- When you sort cards in your hand, what is true about the cards you have already placed?
- To insert a new card, which cards move, and in which direction?
- How much work does insertion sort do on an array that is already sorted?
Hints
Brute force, and why it fails
Inserting by swapping neighbours one at a time works too, but it does three writes per step instead of one. Shifting into a gap is the cleaner version. Like the other simple sorts, the worst case is O(n²), but insertion sort is very fast on input that is already nearly sorted, which is why real libraries use it for small pieces.
The key insight
The left part is always a sorted hand. Each new element only has to walk left past the bigger values, so a nearly sorted array costs almost nothing.
Dry run
| current | 3 |
|---|
nums = [4, 3, 1, 2]. The first card on its own is a sorted hand. Take nums[1] = 3 as the card to insert.
The plan
for i from 1 to n - 1:
current = nums[i]
j = i - 1
while j >= 0 and nums[j] > current:
nums[j + 1] = nums[j] # shift a bigger value right
j = j - 1
nums[j + 1] = current # drop into the gap
return nums
Complexity
- Time
O(n²)- Space
O(1)
The worst case is a reversed array, about n²/2 shifts. A sorted array takes n - 1 comparisons and no shifts. The sort works inside the array.
Edge cases
- One element: the loop does not run.
- Already sorted: each
currentstops at once. - Equal values stop the shifting (
>and not>=), so insertion sort is stable. - The new smallest value walks all the way to index 0, which is why the loop checks
j >= 0.
I've built my logic, show the code
Java
class Solution {
public int[] insertionSort(int[] nums) {
for (int i = 1; i < nums.length; i++) {
int current = nums[i]; // the card to insert
int j = i - 1;
while (j >= 0 && nums[j] > current) {
nums[j + 1] = nums[j]; // shift bigger values one place right
j--;
}
nums[j + 1] = current; // drop it into the gap
}
return nums;
}
}C++
class Solution {
public:
vector<int> insertionSort(vector<int>& nums) {
for (int i = 1; i < static_cast<int>(nums.size()); i++) {
int current = nums[i]; // the card to insert
int j = i - 1;
while (j >= 0 && nums[j] > current) {
nums[j + 1] = nums[j]; // shift bigger values one place right
j--;
}
nums[j + 1] = current; // drop it into the gap
}
return nums;
}
};Python
class Solution:
def insertionSort(self, nums):
for i in range(1, len(nums)):
current = nums[i] # the card to insert
j = i - 1
while j >= 0 and nums[j] > current:
nums[j + 1] = nums[j] # shift bigger values one place right
j -= 1
nums[j + 1] = current # drop it into the gap
return numsCommon mistakes
- Forgetting
j >= 0, so the loop readsnums[-1]. - Writing
currentintonums[j]instead ofnums[j + 1]. - Overwriting
nums[i]before saving it incurrent.