What is Merge Sort?
Merge Sort takes the divide-and-conquer route: keep splitting the array in half until you're left with pieces of a single element each (which are trivially sorted), then merge those pieces back together two at a time, producing bigger and bigger sorted chunks until only one sorted array remains.
Algorithm Steps
- Divide:
- Find the middle point to divide the array into two halves
- Recursively call merge sort on the first half
- Recursively call merge sort on the second half
- Merge:
- Create temporary arrays for both halves
- Compare elements from each half and merge them in order
- Copy any remaining elements from either half
Time Complexity
- Best Case: O(n log n) (already sorted, but still needs all comparisons)
- Average Case: O(n log n)
- Worst Case: O(n log n) (consistent performance)
The log n factor comes from the division steps, while the n factor comes from the merge steps.
Time Complexity Analysis
Space Complexity
Merge Sort requires O(n) additional space for the temporary arrays during merging. This makes it not an in-place sorting algorithm, unlike Insertion Sort or Bubble Sort.
Advantages
- Stable sorting (maintains relative order of equal elements)
- Excellent for large datasets (consistent O(n log n) performance)
- Well-suited for external sorting (sorting data too large for RAM)
- Easily parallelizable (divide steps can be done concurrently)
Disadvantages
- Requires O(n) additional space (not in-place)
- Slower than O(n²) algorithms for very small datasets due to recursion overhead
- Not as cache-efficient as some other algorithms (e.g., QuickSort)
Merge Sort is particularly useful when sorting linked lists (where random access is expensive) and is the algorithm of choice for many standard library sorting implementations when stability is required. It's also commonly used in external sorting where data doesn't fit in memory.