1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Insertion Sort
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
19Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Insertion Sort

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
19Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Insertion Sort

Overview

Insertion Sort is a simple, intuitive sorting algorithm. It builds the final sorted array one item at a time. It works exactly how most humans sort a hand of playing cards: you take one card, compare it to the sorted cards in your hand, and insert it into its exact correct position.

Algorithmically, it conceptually divides the array into two parts: a 'sorted' left half and an 'unsorted' right half. It iterates through the unsorted half, takes an element, and shifts all larger elements in the sorted half to the right to make room for it.

While its worst-case time complexity is O(N^2), it is remarkably efficient for very small datasets or arrays that are already mostly sorted. In fact, modern hybrid sorting algorithms (like Java's default Arrays.sort(), which uses Timsort) switch to Insertion Sort under the hood when the array chunks get small enough (around 32 elements).

Syntax

Standard Insertion Sort
java
public class Sort {
    public static void insertionSort(int[] arr) {
        // Start from index 1 (assume index 0 is initially 'sorted')
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i]; // The item we want to insert
            int j = i - 1;
            
            // Move elements of arr[0..i-1] that are greater than key
            // one position ahead of their current position
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j]; // Shift the larger element right
                j = j - 1;           // Move index backwards
            }
            
            // Insert the key into its correct sorted position
            arr[j + 1] = key;
        }
    }
}

Common Pitfalls

  • Using standard swapping instead of shifting. While you can implement insertion sort by continuously swapping the key with the element before it, shifting is faster. Shifting only requires one assignment per comparison (arr[j+1] = arr[j]), whereas swapping requires three assignments (using a temp variable).
  • Going out of bounds. The inner while loop must always check j >= 0 BEFORE trying to access arr[j]. If you swap the conditions to arr[j] > key && j >= 0, Java evaluates left-to-right, throws an ArrayIndexOutOfBoundsException when j is -1, and crashes.
  • Using it for large datasets. Insertion sort is strictly O(N^2). If you use it on an array of 100,000 items, it will take billions of operations and visibly hang your application. It is only for small or nearly-sorted data.

Interview Questions

What is the Best Case time complexity of Insertion Sort?

O(N). If the array is already perfectly sorted, the inner while loop condition (arr[j] > key) immediately fails every time. The outer loop runs N times, doing O(1) work each time. This makes it vastly superior to Selection Sort or Bubble Sort on nearly-sorted data.

Is Insertion Sort a 'Stable' sort?

Yes. A stable sort preserves the relative order of equal elements. Because the while loop only shifts elements that are strictly greater (>) than the key, an element will never jump ahead of another element with the exact same value.

Real-World Example

Timsort (the default sorting algorithm in Python and Java for Objects) splits massive arrays into tiny 'Runs' of 32-64 elements. It uses Insertion Sort to perfectly sort these tiny runs (because Insertion Sort is lightning fast on tiny arrays with zero overhead), and then uses Merge Sort to stitch the runs together.

example
java
// Conceptual snippet of how Timsort utilizes Insertion Sort
public void timSort(int[] arr) {
    int RUN = 32;
    // Sort tiny chunks using Insertion Sort
    for (int i = 0; i < arr.length; i += RUN) {
        insertionSort(arr, i, Math.min(i + RUN - 1, arr.length - 1));
    }
    
    // Merge the sorted chunks...
}

Check Your Knowledge

Test your understanding of Insertion Sort with these quick questions.

Question 1

What real-world analogy best describes Insertion Sort?

Question 2

In what scenario does Insertion Sort achieve O(N) performance?

Question 3

Is Insertion Sort an In-Place algorithm?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Insertion Sort

Overview

Insertion Sort is a simple, intuitive sorting algorithm. It builds the final sorted array one item at a time. It works exactly how most humans sort a hand of playing cards: you take one card, compare it to the sorted cards in your hand, and insert it into its exact correct position.

Algorithmically, it conceptually divides the array into two parts: a 'sorted' left half and an 'unsorted' right half. It iterates through the unsorted half, takes an element, and shifts all larger elements in the sorted half to the right to make room for it.

While its worst-case time complexity is O(N^2), it is remarkably efficient for very small datasets or arrays that are already mostly sorted. In fact, modern hybrid sorting algorithms (like Java's default Arrays.sort(), which uses Timsort) switch to Insertion Sort under the hood when the array chunks get small enough (around 32 elements).

Syntax

Standard Insertion Sort
java
public class Sort {
    public static void insertionSort(int[] arr) {
        // Start from index 1 (assume index 0 is initially 'sorted')
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i]; // The item we want to insert
            int j = i - 1;
            
            // Move elements of arr[0..i-1] that are greater than key
            // one position ahead of their current position
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j]; // Shift the larger element right
                j = j - 1;           // Move index backwards
            }
            
            // Insert the key into its correct sorted position
            arr[j + 1] = key;
        }
    }
}

Common Pitfalls

  • Using standard swapping instead of shifting. While you can implement insertion sort by continuously swapping the key with the element before it, shifting is faster. Shifting only requires one assignment per comparison (arr[j+1] = arr[j]), whereas swapping requires three assignments (using a temp variable).
  • Going out of bounds. The inner while loop must always check j >= 0 BEFORE trying to access arr[j]. If you swap the conditions to arr[j] > key && j >= 0, Java evaluates left-to-right, throws an ArrayIndexOutOfBoundsException when j is -1, and crashes.
  • Using it for large datasets. Insertion sort is strictly O(N^2). If you use it on an array of 100,000 items, it will take billions of operations and visibly hang your application. It is only for small or nearly-sorted data.

Interview Questions

What is the Best Case time complexity of Insertion Sort?

O(N). If the array is already perfectly sorted, the inner while loop condition (arr[j] > key) immediately fails every time. The outer loop runs N times, doing O(1) work each time. This makes it vastly superior to Selection Sort or Bubble Sort on nearly-sorted data.

Is Insertion Sort a 'Stable' sort?

Yes. A stable sort preserves the relative order of equal elements. Because the while loop only shifts elements that are strictly greater (>) than the key, an element will never jump ahead of another element with the exact same value.

Real-World Example

Timsort (the default sorting algorithm in Python and Java for Objects) splits massive arrays into tiny 'Runs' of 32-64 elements. It uses Insertion Sort to perfectly sort these tiny runs (because Insertion Sort is lightning fast on tiny arrays with zero overhead), and then uses Merge Sort to stitch the runs together.

example
java
// Conceptual snippet of how Timsort utilizes Insertion Sort
public void timSort(int[] arr) {
    int RUN = 32;
    // Sort tiny chunks using Insertion Sort
    for (int i = 0; i < arr.length; i += RUN) {
        insertionSort(arr, i, Math.min(i + RUN - 1, arr.length - 1));
    }
    
    // Merge the sorted chunks...
}

Check Your Knowledge

Test your understanding of Insertion Sort with these quick questions.

Question 1

What real-world analogy best describes Insertion Sort?

Question 2

In what scenario does Insertion Sort achieve O(N) performance?

Question 3

Is Insertion Sort an In-Place algorithm?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A