EN
TypeScript - merge two sorted arrays in optimal way
3
points
In this short article, we would like to show how to merge two sorted arrays in an optimal way in TypeScript.
The below solution:
- requires sorted arrays on input,
- has
O(n1 + n2)
complexity.
Practical example:
const mergeArrays = (a: number[], b: number[]): number[] => {
const result = Array(a.length + b.length);
let i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
result[k++] = a[i] < b[j] ? a[i++] : b[j++];
}
while (i < a.length) {
result[k++] = a[i++];
}
while (j < b.length) {
result[k++] = b[j++];
}
return result;
};
// Usage example:
const a: number[] = [1, 2, 4];
const b: number[] = [3, 5, 6];
const result: number[] = mergeArrays(a, b);
console.log(result);
Output:
[1, 2, 3, 4, 5, 6]