Insertion Sort in Java: Program and Logic
Sort an integer array in ascending order using insertion sort.
- Time
O(n^2) worst, O(n) best - Space
O(1) - Hints3
- Read3 min
Insertion sort in Java keeps the left part of the array sorted. It takes the next value as a key, shifts larger values one place right, and puts the key in the gap. It takes O(n) time on a sorted array and O(n^2) in the worst case, with O(1) extra space. It is stable.
Problem statement
Write a program for insertion sort in Java. Given an int array, sort it in
ascending order in place, without Arrays.sort.
Think of playing cards. You hold sorted cards in one hand. You take a new card, move the bigger cards to the right, and insert the new one in the gap.
An integer array arr of length n.
The same array in ascending order.
Examples
[7, 3, 5, 1][1, 3, 5, 7]3, 5 and 1 are inserted one after another into the sorted left part.
[2, 2, 0][0, 2, 2]The equal values keep their order, and 0 moves to the front.
Constraints
- 0 <= n <= 5000, as the worst time is quadratic
- Duplicates and negative numbers are allowed
Think before you code
Reveal the questions to ask yourself first
- Why can you treat index 0 as already sorted?
- Why must the current value be saved before shifting?
- When should the shifting stop?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- For
ifrom 1 ton - 1, savekey = arr[i]and setj = i - 1. - While
j >= 0andarr[j] > key, copyarr[j]toarr[j + 1]and reducej. - Put
keyatarr[j + 1].
The check j >= 0 must come first. Java stops at the first false part of &&, so
arr[-1] is never read. See operators in Java.
Dry run
Walk through the example step by step
Insertion sort in Java example with [7, 3, 5, 1]:
i | key | shifted right | array after
--+-----+---------------+--------------
1 | 3 | 7 | [3, 7, 5, 1]
2 | 5 | 7 | [3, 5, 7, 1]
3 | 1 | 7, 5, 3 | [1, 3, 5, 7]
Solution
Reveal the full Java solution
import java.util.Arrays;
public class InsertionSort {
static void sort(int[] arr) {
for (int i = 1; i < arr.length; 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;
}
}
public static void main(String[] args) {
int[] a = {7, 3, 5, 1};
sort(a);
System.out.println(Arrays.toString(a));
int[] b = {2, 2, 0};
sort(b);
System.out.println(Arrays.toString(b));
}
}Output of this insertion sort in Java code:
[1, 3, 5, 7]
[0, 2, 2]
Insertion sort in Java: explanation of the key lines
keyholds the value while its old place is overwritten.- The
whileloop shifts. It does not swap, so each step is one write. - After the loop,
jis one place left of the gap. So the key goes toj + 1. - The test
arr[j] > keyleaves equal values alone, which makes the sort stable.
Insertion sort in Java using for loop
The inner loop can also be a for loop that swaps neighbours until the value fits.
import java.util.Arrays;
public class InsertionFor {
public static void main(String[] args) {
int[] a = {12, 11, 13, 5, 6};
for (int i = 1; i < a.length; i++) {
for (int j = i; j > 0 && a[j - 1] > a[j]; j--) {
int t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
System.out.println(Arrays.toString(a));
}
}
}
It prints the array after each insert:
[11, 12, 13, 5, 6]
[11, 12, 13, 5, 6]
[5, 11, 12, 13, 6]
[5, 6, 11, 12, 13]
Insertion sort in Java program for descending order
Shift values that are smaller than the key.
import java.util.Arrays;
public class InsertionDescending {
public static void main(String[] args) {
int[] a = {7, 3, 5, 1};
for (int i = 1; i < a.length; i++) {
int key = a[i];
int j = i - 1;
while (j >= 0 && a[j] < key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
System.out.println(Arrays.toString(a));
}
}
[7, 5, 3, 1]
When is it fast?
| Input | Work | Time |
|---|---|---|
| Already sorted | One check per element | O(n) |
| Nearly sorted | A few shifts per element | Close to O(n) |
| Random | About n²/4 shifts | O(n²) |
| Reverse order | n(n - 1) / 2 shifts | O(n²) |
So insertion sort suits small or nearly sorted arrays. For large random data, use merge sort. Compare it with bubble sort and selection sort. For step-by-step Java learning, see the Java full stack course.
O(n^2) worst, O(n) bestO(1)Review before the interview
Common mistakes
- Not saving the key, so the value is lost after the first shift.
- Writing arr[j] > key && j >= 0, which reads arr[-1] and throws an error.
- Putting the key at arr[j] instead of arr[j + 1].
- Using >=, which moves equal values and makes the sort unstable.
Edge cases to test
- Empty array or one element: the loop does not run.
- Already sorted: no shifts.
- The smallest value is last: it moves to index 0.
- Repeated and negative values.
Interview follow-ups
- Can binary search reduce the comparisons? Does it reduce the shifts?
- How would you insert one new value into a sorted array?
- Why do some library sorts use insertion sort for small parts?
Keep practising
Bubble Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemSelection Sort in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemCheck Whether an Array Is Sorted
Hints · Dry run · SolutionSolve Related learningArrays
TutorialLearn Related learningLoops
TutorialLearn Related learningCoding Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
