Languages
[Edit]
EN

TypeScript - merge two sorted arrays in optimal way

3 points
Created by:
a_horse
538

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]

 

See also

  1. JavaScript - merge two sorted arrays in optimal way 
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join