EN
JavaScript - merge two sorted arrays in optimal way
4 points
In this short article, we would like to show how to merge two sorted arrays in an optimal way in JavaScript.
The below solution:
- requires sorted arrays on input,
- has
O(n1 + n2)
complexity.
Practical example:
xxxxxxxxxx
1
const mergeArrays = (a, b) => {
2
const result = Array(a.length + b.length);
3
let i = 0, j = 0, k = 0;
4
while (i < a.length && j < b.length) {
5
result[k++] = (a[i] < b[j] ? a[i++] : b[j++]);
6
}
7
while (i < a.length) {
8
result[k++] = a[i++];
9
}
10
while (j < b.length) {
11
result[k++] = b[j++];
12
}
13
return result;
14
};
15
16
17
// Usage example:
18
19
const a = [1, 2, 4];
20
const b = [3, 5, 6];
21
22
const result = mergeArrays(a, b);
23
24
console.log(result); // [1, 2, 3, 4, 5, 6]