Loading algorithms…
Loading visualizer…
Divide-and-conquer sorting that recursively halves the array and merges the sorted pieces. Guaranteed O(n log n) and stable.
Main array + auxiliary buffer used by the merge step
Merge sort is a divide-and-conquer algorithm that recursively splits the array in half, sorts each half, and merges the two sorted halves back together. Invented by John von Neumann in 1945, it's the canonical O(n log n) comparison sort and one of the pillars of standard library implementations.
[lo…hi] at the midpointmid = ⌊(lo+hi)/2⌋.[lo…mid] and the right half [mid+1…hi]. Each recursive call halves the range, so the depth of recursion is⌈log₂ n⌉.The merge phase needs to look at both halves simultaneously while writing back into the same array, which would clobber unread data. The textbook solution is to copy each half into an auxiliary buffer first, then walk those buffers with two pointers. This costs O(n) extra space but lets the merge run in a single linear pass per level.
💡 Stability: Merge sort preserves the relative order of equal elements — useful when sorting records by a secondary key (e.g. users by last name, then by first name). Quick sort, by contrast, is not stable in its standard in-place form.
Watch the recursion split the array at depth ⌈log₂ n⌉, then merge the sorted pieces back together.