Browse curriculum

Merge Sort

Merge sort is a divide-and-conquer sorting algorithm that guarantees O(N log N) performance.

Intuition

If you have a messy stack of papers, you can split it iteratively until you have single papers (which are trivially sorted). Then you merge small sorted stacks into larger ones until you have one sorted stack.

Concept

  • Divide & Conquer: Recursively splits the array into two halves until size 1.
  • Merge: The core operation. Merges two sorted sub-arrays into a single sorted array.
  • Complexity: Guarantees O(N log N) time complexity in all cases.

How it Works

Algorithm:

  1. Find middle index.
  2. Recursively sort left half.
  3. Recursively sort right half.
  4. Merge the two sorted halves into a temporary array (or overwrite).

Step-by-Step Breakdown

Watch the visualization:

  • Blue Highlight: Visualizes the current sub-array being merged (Deep in recursion).
  • Red Bar: Value being overwritten in the original array from the sorted result.
  • Green: Fully sorted array at the end.

When to Use

  • Large Datasets: Guaranteed efficiency where O(N²) sorts fail.
  • Linked Lists: Can sort linked lists in O(N log N) without extra space.
  • Stable Sort Needed: When relative order matters.

When NOT to Use

  • Space Constraints: Requires O(N) auxiliary space for arrays.
  • Very Small N: Overhead of recursion makes it slower than Insertion Sort for tiny arrays.

How to Identify

"Guaranteed O(N log N)", "Sort Linked List", "External Sorting".

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is the space complexity of Merge Sort?

Merge Sort requires O(n) extra space for the temporary arrays used during the merge process.


Is Merge Sort a stable algorithm?

Yes, Merge Sort is stable, making it perfect for sorting complex objects by multiple criteria.


Merge Sort vs Quick Sort?

Merge Sort is consistently O(n log n) but uses more memory. Quick Sort is often faster in practice but can hit O(n²) in the worst case.