Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this JavaScript DSA implementation can be compared directly with the other languages.
divide and conquer
Each recursive call solves a smaller sorted subproblem.
merge step
Two sorted halves are combined by repeatedly taking the smaller front item.
Visual walkthrough
Basic Implementation
basic.js
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));
const merged = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged.push(left[i++]);
} else {
merged.push(right[j++]);
}
}
return merged.concat(left.slice(i)).concat(right.slice(j));
}
const arr = [5, 1, 4, 2, 8];
console.log(JSON.stringify(mergeSort(arr)));
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- JavaScript stores the input as a
constArrayofNumbervalues.mergeSortreturns a sorted array instead of mutating the originalarr; only length-0 or length-1 base cases return the existing array reference. - Each recursive split uses
Math.floor(values.length / 2)plusvalues.slice(0, mid)andvalues.slice(mid), so the left and right halves are copied arrays before the recursive calls. mergestate is held in a freshmergedarray and index variablesiandj. The numeric comparisonleft[i] <= right[j]takes the left value on ties, preserving stability for equalNumbervalues.- Values are appended with
merged.push(...); remaining tails are appended viamerged.concat(left.slice(i)).concat(right.slice(j)), which allocates the tail slices and concatenated result arrays. - The replay-visible states split
[5, 1, 4, 2, 8]into[5, 1]and[4, 2, 8], sort them to[1, 5]and[2, 4, 8], then merge[1, 2, 4, 5, 8].console.log(JSON.stringify(mergeSort(arr)))creates the compact output string[1,2,4,5,8]; temporary arrays and strings are handled by the JavaScript runtime GC.