Merge Sort

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Merge Sort

Approach

Recursively divide the array in half until single elements remain (base case). Then merge pairs of sorted subarrays by comparing elements from each, always taking the smaller one. The merge step runs in O(n) and there are O(log n) levels of recursion.

Complexity Analysis

Time
O(n log n)
Space
O(n)

Pattern

Divide and Conquer Sort

Why It Works

Dividing halves the problem size each time (log n levels). Merging two sorted arrays takes linear time because both are already sorted — just compare front elements. Stability is preserved because equal elements from the left array are taken first.

Updated Feb 2026