Insertion Sort

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given an array of integers, sort it in non-decreasing order using **Insertion Sort** — build up a sorted prefix one element at a time, inserting each new element into its correct position within that prefix. Insertion sort mirrors how most people sort a hand of playing cards: cards already in hand stay in order, and each new card drawn gets slotted into the right spot among them. It's not the fastest general-purpose sort, but on nearly-sorted data it does very little work, and it needs no extra memory.

Test Case 1:

Input:arr = [7, 2, 9, 4, 2, 8]
Output:[2, 2, 4, 7, 8, 9]
Explanation:A typical unsorted array with a repeated value.

Test Case 2:

Input:arr = []
Output:[]
Explanation:An empty array is already sorted.

Test Case 3:

Input:arr = [5]
Output:[5]
Explanation:A single element is already sorted.

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

Good

Grow 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.

TimeO(n²)
SpaceO(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

Optimal

Same 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.

TimeO(n²)
SpaceO(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}

Related Problems