Insertion Sort
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ arr.length ≤ 200 - ◆
-1000 ≤ arr[i] ≤ 1000 - ◆
Sort in non-decreasing order
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Adjacent Swaps
GoodGrow a sorted prefix one element at a time. For each new element, repeatedly swap it one step to the left with its neighbor as long as it's smaller — the same three-assignment swap used everywhere else, just walked backward until the element lands in the right spot. Correct, but every step of the walk costs a full swap (three writes) even though only one value is actually moving.
O(n²)O(1)1class Solution {
2 public int[] insertionSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 1; i < n; i++) {
5 int j = i;
6 while (j > 0 && arr[j] < arr[j - 1]) {
7 int temp = arr[j];
8 arr[j] = arr[j - 1];
9 arr[j - 1] = temp;
10 j--;
11 }
12 }
13 return arr;
14 }
15}Optimal — Shift and Insert
OptimalSame growing-sorted-prefix idea, but skip the wasted work. Save the new element as key once, then shift every larger element in the sorted prefix one step right (a single write each, not a three-write swap) to open a gap, and drop key into that gap at the end. Same worst-case time as the swap version, but noticeably fewer writes in practice — this is the insertion sort taught in every algorithms course.
O(n²)O(1)1class 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 while (j >= 0 && arr[j] > key) {
8 arr[j + 1] = arr[j];
9 j--;
10 }
11 arr[j + 1] = key;
12 }
13 return arr;
14 }
15}