Easy Array Problems Java

Insertion Sort in Java: Program and Logic

Sort an integer array in ascending order using insertion sort.

  • TimeO(n^2) worst, O(n) best
  • SpaceO(1)
  • Hints3
  • Read3 min
Quick answer

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.

Insertion sortShifting elementsStable sorting
1

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.

Input

An integer array arr of length n.

Output

The same array in ascending order.

Examples

Example 1
Input[7, 3, 5, 1]
Output[1, 3, 5, 7]

3, 5 and 1 are inserted one after another into the sorted left part.

Example 2
Input[2, 2, 0]
Output[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
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start the outer loop at index 1.
2 Hint 2
Save arr[i] in key. Shifting will overwrite that place.
3 Hint 3
Shift while j >= 0 and arr[j] > key, then set arr[j + 1] = key.
4

Approach

Reveal the step-by-step approach
  1. For i from 1 to n - 1, save key = arr[i] and set j = i - 1.
  2. While j >= 0 and arr[j] > key, copy arr[j] to arr[j + 1] and reduce j.
  3. Put key at arr[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.

5

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]
6

Solution

Reveal the full Java solution
Solution.java
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

  • key holds the value while its old place is overwritten.
  • The while loop shifts. It does not swap, so each step is one write.
  • After the loop, j is one place left of the gap. So the key goes to j + 1.
  • The test arr[j] > key leaves 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.

TimeO(n^2) worst, O(n) best
SpaceO(1)
7

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

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us