Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Merging sorted arrays together JavaScript
Merging two sorted arrays in JavaScript involves combining them into a single sorted array. This is a common problem in data structures and algorithms that uses the greedy approach to efficiently merge pre-sorted arrays.
What are Sorted Arrays?
Sorted arrays are arrays where elements are arranged in a specific order, typically ascending. In JavaScript, arrays are resizable collections that can be sorted using the built-in sort() method.
// Array before sorting
var arr = [2, 5, 1, 3, 6, 9, 7];
console.log("Before sorting:", arr);
// Array after sorting
arr.sort((a, b) => a - b);
console.log("After sorting:", arr);
Before sorting: [ 2, 5, 1, 3, 6, 9, 7 ] After sorting: [ 1, 2, 3, 5, 6, 7, 9 ]
Understanding the Problem
Given two already sorted arrays, we need to merge them into a single sorted array. The algorithm compares elements from both arrays and selects the smaller one at each step, following a greedy approach.
Algorithm Steps
Step 1: Initialize two pointers for both arrays and one for the result array
Step 2: Compare elements at current positions
Step 3: Add the smaller element to result and advance its pointer
Step 4: Continue until one array is exhausted
Step 5: Add remaining elements from the other array
Implementation
function mergeSortedArrays(array1, array2) {
let mergedArray = [];
let i = 0; // pointer for array1
let j = 0; // pointer for array2
// Compare elements from both arrays
while (i
Array 1: [ 1, 5, 9, 12 ]
Array 2: [ 2, 6, 8, 15, 20 ]
Merged Array: [ 1, 2, 5, 6, 8, 9, 12, 15, 20 ]
Using Built-in Methods
Alternatively, you can use JavaScript's spread operator and sort method, though this is less efficient:
function mergeAndSort(arr1, arr2) {
return [...arr1, ...arr2].sort((a, b) => a - b);
}
const nums1 = [1, 3, 5];
const nums2 = [2, 4, 6];
console.log("Simple merge:", mergeAndSort(nums1, nums2));
Simple merge: [ 1, 2, 3, 4, 5, 6 ]
Time and Space Complexity
| Method | Time Complexity | Space Complexity | Efficiency |
|---|---|---|---|
| Two-pointer approach | O(n + m) | O(n + m) | Optimal |
| Concat + Sort | O((n + m) log(n + m)) | O(n + m) | Less efficient |
Where n and m are the lengths of the input arrays.
Conclusion
The two-pointer approach is the most efficient method for merging sorted arrays with O(n + m) time complexity. This greedy algorithm takes advantage of the pre-sorted nature of input arrays to avoid unnecessary comparisons.
