Price your future right. 60% off with code BLACKSCHOLES at USD checkout. Offer ends in 1d 16h 01m 38s1 days 16 hours 1 minutes 38 seconds.
Price your future right. 60% off with code BLACKSCHOLES at USD checkout. Offer ends in 1d 16h 01m 38s1 days 16 hours 1 minutes 38 seconds.

Sign in to watch this lesson
Algorithms - Sorting and Searching · 5:16
Merge sort splits [2, 4, 1, 3, 5] in half until every piece is a single value, then merges back up with two pointers. In the top merge, every time a right-half value jumps ahead of the values still waiting on the left it forms an inversion with each of them, so one extra line (add mid - i) counts all inversions in O(n log n). We see why every level of the recursion costs n, measure the comparisons against the lower bound and the brute-force count on this Mac, and cover the traps: ties, 64-bit counters, one shared buffer, and what libc++'s std::stable_sort does.