Sorting

Merge Sort

Size:15
Visualizer is loading, please wait...
Execution Narrative
Step 1 of 147Start
Line 1
Starting Merge Sort on array of 15 elements.
Comparisons0
Swaps0
Operations0

Overview & Concept

Merge Sort is a classic Divide-and-Conquer sorting algorithm invented by John von Neumann. It recursively splits the array into two halves until single-element subarrays are reached, then merges the sorted halves back together in linear time, guaranteeing O(n log n) worst-case time complexity.

How It Works

Divide: Recursively split array at midpoint into left and right halves.

Conquer: Base case is reached when subarray size is 1 (trivially sorted).

Combine (Merge): Two sorted subarrays are merged into a single sorted buffer using two pointer comparisons.

Stability Guaranteed: Equal elements from the left subarray are always chosen first during merge.

Step-by-Step Execution

1. Calculate MidpointCompute mid = Math.floor((low + high) / 2).
2. Recursive Left & RightRecursively call mergeSort(low, mid) and mergeSort(mid + 1, high).
3. Merge Two Sorted HalvesCompare pointers in left and right buffers; copy smaller item into temporary result.
4. Copy Back to Main ArrayCopy sorted merged elements from temporary buffer back into original array.

Asymptotic Complexity Analysis

MetricBest CaseAverage CaseWorst CaseSpace Complexity
Complexity BoundO(n log n)O(n log n)O(n log n)O(n)
ExplanationOptimal input arrangement minimizing operations.Expected time for uniformly distributed randomized inputs.Adversarial degenerate conditions requiring full traversal.Auxiliary memory allocated beyond original input size.

Pseudocode & Invariants

Algorithm Logic
procedure mergeSort(A, left, right):
  if left >= right: return
  mid = floor((left + right) / 2)
  split into A[left..mid] & A[mid+1..right]
  mergeSort(A, left, mid); mergeSort(A, mid + 1, right)
  merge(left, mid, right):
    compare left[i] and right[j]
    place smaller into merged A[k]
    copy remaining elements
  return A
Algorithmic Invariants
  • Subarray Sortedness: After merge(low, mid, high), the subarray A[low..high] is strictly sorted.
Correctness Guarantee: Invariants hold true prior to loop entry, are preserved during every iteration, and guarantee correct post-condition upon termination.

Advantages & Disadvantages

Key Advantages

  • •Guaranteed O(n log n) time complexity in all cases (best, average, worst).
  • •Stable sorting: preserves original ordering of duplicate keys.
  • •Predictable performance with zero worst-case degradation.
  • •Excellent for external sorting of files that exceed available RAM.

Trade-offs & Limitations

  • •Requires O(n) auxiliary memory for temporary merge buffers.
  • •Higher constant factors than Quick Sort for in-memory primitive arrays.

Real-World Applications

External File Sorting

Sorting terabyte-scale datasets on disk by sorting chunks and performing multi-way merges.

Standard Library Stable Sorting

Java Object sorting and Python Timsort (derived from Merge Sort).

Decision Guide: When to Use

Ideal Scenarios

  • ✓When stable sorting is strictly required.
  • ✓When worst-case O(n log n) guarantees are essential.
  • ✓When sorting linked lists or disk-resident files.

Consider Alternatives When

  • ✕When auxiliary memory is tightly constrained and O(1) in-place sorting is required.

Compare trade-offs and complexity across complementary tools in AlgoViz.