Imagine you're sorting a hand of playing cards. You pick up one card at a time and slide it left past all larger cards until it finds its correct position in the sorted portion.
for i = 1 to n-1:
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = key
| Case | Time | When |
|---|---|---|
| Best | O(n) | Array already sorted |
| Average | O(n²) | Random order |
| Worst | O(n²) | Reverse sorted |
| Space | O(1) | In-place sorting |
Insertion sort excels when the data is nearly sorted or the array is small. It's often used as the base case for hybrid algorithms like Timsort (used in Python and Java) when subarrays become small enough that the overhead of more complex algorithms isn't worth it.