Insertion Sort
Idea Like You Are 10
Imagine you are holding playing cards.
You pick one card at a time and slide it into the correct spot among the cards already in your hand.
That is exactly how Insertion Sort works.
Small Example
Sort:
Start:
[5] is the sorted part.
Insert 3:
Insert 8:
Insert 1:
Diagram
Algorithm
- Pretend the first element is already sorted
- Take the next element
- Move bigger elements one step right
- Put the current element in its correct place
- Repeat
Pseudocode
Time Complexity
| Case | Time |
|---|---|
| Best | O(n) |
| Average | O(n^2) |
| Worst | O(n^2) |
Why This Time Complexity?
Best Case: O(n)
If the list is already sorted, each new item is already in the right place.
So we only do one quick check for each element.
Average Case: O(n^2)
Usually, each new element must move left a little bit.
That creates many shifts over and over.
Worst Case: O(n^2)
If the list is in reverse order, every new element must move across almost the whole sorted part.
Example:
The total work becomes:
That adds up to about n^2.
Space Complexity
O(1) because it sorts in place.
Performance
- Great for very small lists
- Great when the list is already almost sorted
- Slow for large random lists
When To Use
- Small arrays
- Nearly sorted data
- As a helper inside bigger sorting systems