typescript
function mergeSort<T>(
arr: T[],
compareFn: (a: T, b: T) => number = (a, b) => (a > b ? 1 : a < b ? -1 : 0)
): T[] {
if (arr.length <= 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
return merge(mergeSort(left, compareFn), mergeSort(right, compareFn), compareFn);
}
function merge<T>(
left: T[],
right: T[],
compareFn: (a: T, b: T) => number
): T[] {
const result: T[] = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (compareFn(left[leftIndex], right[rightIndex]) <= 0) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
// Add remaining elements
while (leftIndex < left.length) {
result.push(left[leftIndex]);
leftIndex++;
}
while (rightIndex < right.length) {
result.push(right[rightIndex]);
rightIndex++;
}
return result;
}
// Example usage:
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log(mergeSort(numbers)); // [11, 12, 22, 25, 34, 64, 90]
// With custom comparator for objects
interface Person {
name: string;
age: number;
}
const people: Person[] = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 }
];
const sortedByAge = mergeSort(people, (a, b) => a.age - b.age);
console.log(sortedByAge);
// [{ name: "Bob", age: 25 }, { name: "Alice", age: 30 }, { name: "Charlie", age: 35 }]
// Sort in descending order
const descending = mergeSort(numbers, (a, b) => b - a);
console.log(descending); // [90, 64, 34, 25, 22, 12, 11]
The time complexity is O(n log n) and space complexity is O(n).