Sorting

Insertion Sort

Size:15
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 154Start
Line 1
Starting Insertion Sort on array of 15 elements.
Comparisons0
Swaps0
Operations0

Overview & Concept

Insertion Sort builds the final sorted array one item at a time. It consumes one element per iteration and inserts it into its correct position within the already-sorted prefix by shifting larger elements one position to the right.

How It Works

Incremental Construction: The left prefix is maintained in sorted order at all times.

Key Extraction: The next unsorted element is stored in a temporary variable.

Rightward Shifting: Elements in the sorted prefix greater than the key are shifted right by 1.

Slot Insertion: The key is dropped into the newly opened vacant slot.

Step-by-Step Execution

1. Select KeyExtract element at index i (for i = 1 to n - 1).
2. Scan Sorted PrefixCompare key with elements from i - 1 down to 0.
3. Shift ElementsWhile A[j] > key, copy A[j] to A[j + 1] and decrement j.
4. Write KeyPlace key into A[j + 1].

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n)O(n²)O(n²)O(1)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure insertionSort(A):
  mark A[0] as initially sorted
  for i = 1 to n - 1:
    key = A[i]; j = i - 1
    while j >= 0 and A[j] > key:
      A[j + 1] = A[j]; j--
    A[j + 1] = key
    mark A[0..i] as sorted
  end for
  return A
Algorithmic Invariants
  • Prefix Invariant: At start of iteration i, subarray A[0..i-1] is strictly sorted.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •O(n) adaptive best-case time for nearly-sorted data.
  • •Stable: does not reorder identical elements.
  • •In-place with O(1) space and minimal overhead.
  • •Practical: powers the base cases of hybrid sorting algorithms (Timsort, Introsort).

Trade-offs & Limitations

  • •O(n²) time complexity for reverse-sorted or randomly ordered large datasets.

Real-World Applications

Hybrid Sorting Base Cases

Java Arrays.sort and Python Timsort use Insertion Sort for subarrays of size n ≤ 32.

Online Streaming Data

Sorting data that arrives continuously one item at a time.

Decision Guide: When to Use

Ideal Scenarios

  • ✓When the array is small (n ≤ 30) or already nearly sorted.
  • ✓When streaming elements into a live sorted buffer.

Consider Alternatives When

  • ✕When sorting large random arrays.

Compare trade-offs and complexity across complementary tools in AlgoViz.