How Insertion Sort Works
Insertion sort builds the final sorted array one item at a time by repeatedly picking the next element and inserting it into its correct position among the already-sorted elements. It is efficient for small or nearly sorted datasets.
Take the next unsorted element, compare it backwards through the sorted portion, shifting larger elements to the right until you find the correct position. Insert the element there and repeat for all remaining elements.
Complexity
- Time
- O(n²)
- Space
- O(1)
- Stability
- stable
When to Use Insertion Sort
- Small datasets
- Nearly sorted data where it runs in near-linear time
- Online sorting where elements arrive one at a time