How to use Two Pointers In Javascript
Using two pointers, initialize two indices for the two arrays. Compare elements at these indices, add the smaller element to the result array, and move the corresponding pointer forward. Repeat until one array is fully processed, then add remaining elements from the other array.
Example: In this example the function mergeSortedArraysTwoPointers merges two sorted arrays into one sorted array using two pointers.
function mergeSortedArraysTwoPointers(arr1, arr2) {
let result = [];
let i = 0, j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
result.push(arr1[i]);
i++;
} else {
result.push(arr2[j]);
j++;
}
}
// Add remaining elements from arr1
while (i < arr1.length) {
result.push(arr1[i]);
i++;
}
// Add remaining elements from arr2
while (j < arr2.length) {
result.push(arr2[j]);
j++;
}
return result;
}
let arr1 = [1, 3, 5];
let arr2 = [2, 4, 6];
console.log(mergeSortedArraysTwoPointers(arr1, arr2));
Output
[ 1, 2, 3, 4, 5, 6 ]
JavaScript Program to Merge two Sorted Arrays into a Single Sorted Array
In this article, we will cover how to merge two sorted arrays into a single sorted array in JavaScript.
Given there are two sorted arrays, we need to merge them into a single sorted array in JavaScript. We will see the code for each approach along with the output. Below are the possible approaches that will be discussed in this article:
Approaches to merge two sorted arrays into a single sorted array
Table of Content
- Using the concat() and slice() methods in JavaScript
- Using the Array.reduce() method in JavaScript
- Using Two Pointers
Contact Us