DSA AnimatorREVISION VIDEOS
← Back to problems
New

Merge Sort — LeetCode 912 video explanation

Sort an array in increasing order. Merge sort guarantees O of n log n in every case.

Loading videos…

DSA Animator › DSA Revision › Sorting Algorithms › Merge Sort

Key moments in the Merge Sort video

0:02Problem0:09Example0:15Brute force0:22Key idea0:45Dry run1:11Code1:32Takeaway

What you will learn

Remember: split, sort halves, merge by taking the smaller front. Guaranteed O of n log n, at the cost of extra memory. The video solves Merge Sort (LeetCode 912, Medium) with the Divide and Conquer pattern from the Sorting Algorithms topic, and you can replay every step in the interactive Merge Sort animation.

Merge Sort video transcript

Problem

Sort an array in increasing order. Merge sort guarantees O of n log n in every case.

Example

For 6, 3, 8, 2, 7, 1, 5, 4, the result is 1 to 8.

Brute force

Quadratic sorts are fine for small inputs only. Merge sort splits the work in half again and again.

Key idea

Split the array into two halves. Sort each half recursively, until a part has only one element, which is already sorted. Then merge two sorted halves, by repeatedly taking the smaller front element. Merging two parts costs time proportional to their total length. There are log n levels of halving, so the total is O of n log n.

Dry run

Split down to single elements, and merge pairs: 3 6, then 2 8. Merge those two pairs into 2, 3, 6, 8. On the right side, merge 1 7 and 4 5. Then merge them into 1, 4, 5, 7. Finally merge 2, 3, 6, 8 with 1, 4, 5, 7, always taking the smaller front value. The result is 1, 2, 3, 4, 5, 6, 7, 8.

Code

In code, merge sort returns when the range has one element. It sorts the left half and the right half. The merge step copies the range, and uses two pointers to write back the smaller front each time. Any leftovers are copied at the end. It's O of n log n time and O of n extra space, and it is stable.

Takeaway

Remember: split, sort halves, merge by taking the smaller front. Guaranteed O of n log n, at the cost of extra memory.

More Sorting Algorithms revision videos

← All 185 DSA revision videos