Concept Overview

Insertion Sort builds a sorted array one element at a time by taking an element from the unsorted portion and inserting it into its correct position in the sorted portion. It mimics the way people sort a hand of playing cards.

How It Works

Time and Space Complexity

Why Use Insertion Sort?

Java Implementation

public class InsertionSort {
    public static void insertionSort(int[] arr) {
        int n = arr.length;
        for (int i = 1; i < n; i++) {
            int key = arr[i];
            int j = i - 1;
            // Shift elements of the sorted portion to the right
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            // Place the key in its correct position
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        insertionSort(arr);
        System.out.println("Sorted array: " + java.util.Arrays.toString(arr));
    }
}

Best Practices and Pitfalls