DSA · Patterns, not puzzles
How does merge sort work?
Short answer
Merge sort divides the array in half, recursively sorts each half, then merges the two sorted halves. It runs in O(n log n) time and uses O(n) extra space.
Merge sort is the clearest divide-and-conquer algorithm. The divide step is trivial: split at the midpoint. The combine step does the real work: merge two sorted arrays by repeatedly taking the smaller front element.
function mergeSort(values) {
if (values.length <= 1) return values;
const mid = Math.floor(values.length / 2);
const left = mergeSort(values.slice(0, mid));
const right = mergeSort(values.slice(mid));
return merge(left, right);
}
function merge(left, right) {
const result = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) result.push(left[i++]);
else result.push(right[j++]);
}
while (i < left.length) result.push(left[i++]);
while (j < right.length) result.push(right[j++]);
return result;
}Why the complexity is O(n log n)
- There are log n levels of splitting
- Each level merges a total of n elements
- The merge work is linear per level
- The recursion tree has log n height, so stack usage is O(log n)
The main cost is the auxiliary array used during merging. A linked list can be merged without allocating a new list, which is one reason merge sort is attractive for linked lists. It is also a natural fit for external sorting where data does not fit in memory.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is merge sort stable?
- 2What is the space complexity of merge sort?
- 3Why is merge sort good for linked lists?
- 4How would you count inversions with merge sort?
Say it in the interview
Merge sort splits the array in half until each piece has one element, then merges sorted pieces by taking the smaller front element each time. The divide step creates log n levels, and each level does linear merge work, so the time is O(n log n). It needs O(n) auxiliary space. On ties I take from the left half, which keeps the sort stable.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.