This is my solution to a problem that involves merging two arrays of integers sorted in ascending order into one larger sorted array. The function merges the arrays by comparing elements from each array and appending them to a new array in an orderly fashion.
function mergeSortedArrays(arr1, arr2) {
// Check input
if (arr1.length === 0 && arr2.length === 0) {
return arr1;
} else if (arr1.length === 0) {
return arr2;
} else if (arr2.length === 0) {
return arr1;
}
// Initialize variables
let i = 0, j = 0;
const mergedArray = [];
// Loop through & compare
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
mergedArray.push(arr1[i]);
i++;
} else {
mergedArray.push(arr2[j]);
j++;
}
}
if (j < arr2.length) {
while (j < arr2.length) {
mergedArray.push(arr2[j]);
j++;
}
} else if (i < arr1.length) {
while (i < arr1.length) {
mergedArray.push(arr1[i]);
i++;
}
}
return mergedArray; // O(1)
}
The time complexity of this function has been a point of analysis as it's not solely bound by the length of either array but also influenced by the upper and lower bounds of each array. Further examination beyond linear time complexity, O(n), is required for a precise understanding of its operational efficiency.