Sorting
Merge Sort (Top-Down)
Split the array recursively, sort each half, then merge two sorted runs into one sorted result.
Algorithm
Basic Implementation
basic.ts
function mergeSort(values: number[]): number[] {
if (values.length <= 1) {
return values;
}
const mid: number = Math.floor(values.length / 2);
const left: number[] = mergeSort(values.slice(0, mid));
const right: number[] = mergeSort(values.slice(mid));
const merged: number[] = [];
let i: number = 0;
let j: number = 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: number[] = [5, 1, 4, 2, 8];
console.log(JSON.stringify(mergeSort(arr)));
Complexity
- Time: O(n log n)
- Space: O(n)
- Stable: yes
Implementation notes
- TypeScript declares
mergeSort(values: number[]): number[], so each call accepts and returns arrays ofnumbervalues. - Base cases return the existing short array reference. Larger calls compute
const mid: number = Math.floor(values.length / 2)and allocate copied halves withvalues.slice(0, mid)andvalues.slice(mid). - Merge state is held in
const merged: number[] = []plus typed cursor bindingslet i: numberandlet j: number. - The comparison
left[i] <= right[j]uses numericNumbervalues through TypeScript'snumbertype; taking fromlefton ties preserves equal-value order. - Remaining tails are copied with
left.slice(i)andright.slice(j), then joined into the result withconcat, so this implementation returns a new sorted array instead of mutatingarr. - The replay splits
[5, 1, 4, 2, 8]into[5, 1]and[4, 2, 8], sorts them to[1, 5]and[2, 4, 8], then prints[1,2,4,5,8]viaJSON.stringify(mergeSort(arr)); visible allocation is the input array, copied slice arrays, merge arrays, concat result arrays, and JSON output string.
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.