Merge Sort, explained step by step
Merge Sort is a highly efficient, stable sorting algorithm based on the Divide and Conquer paradigm. It divides the input array into two halves, recursively calls itself for the two halves, and then merges the two sorted halves. It is widely used in systems where stable sorting is required and memory is not a strict constraint.
Intuition: If you have two sorted piles of cards, you can easily merge them into one sorted pile by comparing the top cards. Merge Sort repeatedly halves the deck until every pile is size 1 (which is sorted), then merges them back together.
How it works
- Find the middle point to divide the array into two halves.
- Call mergeSort recursively for the first half.
- Call mergeSort recursively for the second half.
- Merge the two sorted halves back into a single sorted sequence.
Complexity
- Best: O(n log n)
- Average: O(n log n)
- Worst: O(n log n)
- Space: O(n)
- Stable: yes
When to use it
When stable sorting is strictly required and O(n) extra space is acceptable. Highly predictable performance (always O(n log n)).
Interview questions
- Why is Merge Sort preferred for Linked Lists over arrays?
- Can Merge Sort be implemented in-place?
- What is the space complexity of Merge Sort?