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
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n) | O(n²) | O(n²) | O(1) |
| Explanation | Optimal 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
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- Prefix Invariant: At start of iteration i, subarray A[0..i-1] is strictly sorted.
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.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.