Merge Sort
Idea Like You Are 10
Imagine tearing a big pile of cards into smaller and smaller piles until every pile has just one card.
Then you join the piles back together in sorted order.
That is Merge Sort.
Small Example
Sort:
Split:
Single items are already sorted.
Now merge:
Merge the two sorted parts:
Diagram
Algorithm
- Split the array into two halves
- Sort each half
- Merge the two sorted halves
- Repeat until complete
Pseudocode
Time Complexity
| Case | Time |
|---|---|
| Best | O(n log n) |
| Average | O(n log n) |
| Worst | O(n log n) |
Why This Time Complexity?
Merge Sort always:
- splits into halves, which creates about
log nlevels - merges all
nelements at each level
So the work is:
No matter if the input is already sorted or completely messy, the time stays the same.
Space Complexity
O(n) because it usually needs extra arrays while merging.
Performance
- Very reliable
- Good for large data
- Stable sort
- Needs extra memory
When To Use
- When you want guaranteed
O(n log n)time - When stability matters
- When extra memory is okay