Languages
[Edit]
EN

JavaScript - merge two sorted arrays in optimal way

4 points
Created by:
FryerTuck
649

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:

// ONLINE-RUNNER:browser;

const mergeArrays = (a, b) => {
	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 = [1, 2, 4];
const b = [3, 5, 6];

const result = mergeArrays(a, b);

console.log(result);  // [1, 2, 3, 4, 5, 6]

 

See also

  1. TypeScript - 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