
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Merge two sorted arrays to form a resultant sorted array in JavaScript
We are required to write a JavaScript function that takes in two sorted array of numbers. The function should merge the two arrays together to form a resultant sorted array and return that array.
For example β
If the two arrays are β
const arr1 = [2, 6, 6, 8, 9]; const arr2 = [1, 4, 5, 7];
Then the output array should be β
const output = [1, 2, 4, 6, 6, 7, 8, 9];
Example
The code for this will be β
const arr1 = [2, 6, 6, 8, 9]; const arr2 = [1, 4, 5, 7]; const mergeSortedArrays = (arr1 = [], arr2 = []) => { let m = arr1.length; let n = arr2.length; let currentIndex = m + n; const checkNum1HasLargerNumber = (a, b) => { if (a < 0) { return false; }; if (b < 0) { return true; }; return arr1[a] >= arr2[b]; }; m β= 1; n β= 1; while (currentIndexββ) { let hasNums1LargerNumber = checkNum1HasLargerNumber(m, n); arr1[currentIndex] = hasNums1LargerNumber ? arr1[m] : arr2[n]; if (hasNums1LargerNumber) { m β= 1; } else { n β= 1; } }; }; mergeSortedArrays(arr1, arr2); console.log(arr1);
Output
And the output in the console will be β
[ 1, 2, 4, 5, 6, 6, 7, 8, 9 ]
Advertisements