Java ProgramsArraysInsertion Sort

Insertion Sort in Java

intermediate·  Arrays  ·  Sorting

Problem

Insertion sort builds up a sorted section of the array one element at a time, sliding each new element backward into its correct position among the already-sorted elements before it.

Given an array of integers, sort it in ascending order using insertion sort.

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

Java Program

Java
import java.util.Arrays; public class InsertionSort { public static void main(String[] args) { int[] arr = {5, 1, 9, 3, 7}; for (int i = 1; i < arr.length; i++) { int key = arr[i]; int j = i - 1; // Shift every larger element rightward to open a gap for key while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } System.out.println(Arrays.toString(arr)); } }

Output

[1, 3, 5, 7, 9]

Core Logic

Treating the first element as already sorted, then repeatedly picking the next element and shifting it backward past every larger value before it, grows a sorted section one element at a time.

How It Works
  1. 1The outer loop starts at index 1, since a single element is trivially sorted on its own.
  2. 2key holds the value being inserted, and j starts at the index just before it.
  3. 3The inner while loop shifts each element rightward — arr[j + 1] = arr[j] — as long as it's greater than key, opening up a gap.
  4. 4Once the loop stops, arr[j + 1] = key drops the value into the gap it just opened — its correct sorted position.
For [5, 1, 9, 3, 7], inserting 1 shifts 5 rightward and places 1 at the front, producing [1, 5, 9, 3, 7] — repeating this for each remaining element finishes the sort.
💡

Key Point: Unlike bubble or selection sort, insertion sort's inner loop doesn't always run to the end — it stops as soon as it finds an element that's already smaller than key, which is why it performs especially well on data that's already nearly sorted.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: The nested loops shift up to n elements per pass in the worst case, and each shift happens in place using only the key variable.

Key Concepts

for loopwhile loopshifting elements

Related Programs