Merge Sorted Arrays
func mergeSortedArrays(arr1: [Int], arr2: [Int]) -> [Int] { // Handle edge cases where one or both arrays are empty. if arr1.isEmpty { return arr2 } if arr2.isEmpty { return arr1 } var mergedArray: [Int] = [] var i = 0 // Pointer for arr1 var j = 0 // Pointer for arr2 // Merge el...
This function merges two already sorted arrays of integers into a single, new sorted array. It uses a two-pointer approach to efficiently compare elements from both input arrays and build the merged result. This is a cor...
The `mergeSortedArrays` function takes two sorted integer arrays, `arr1` and `arr2`, and returns a new array containing all elements from both, also sorted. It initializes an empty array `mergedArray` to store the result and two pointers, `i` for `arr1` and `j` for `arr2`, both starting at index 0. The main loop continues as long as both pointers are within their respective array bounds. In each iteration, it compares the elements at `arr1[i]` and `arr2[j]`. The smaller element is appended to `mergedArray`, and its corresponding pointer is incremented. After the main loop finishes, one of the arrays might still have remaining elements. Two separate `while` loops are used to append any leftover elements from `arr1` and then from `arr2` to `mergedArray`. The time complexity is O(m + n), where m and n are the lengths of `arr1` and `arr2` respectively, because each element from both arrays is examined and appended exactly once. The space complexity is O(m + n) because a new array is created to store the merged result. Edge cases like empty input arrays are handled at the beginning, returning the non-empty array or an empty array if both are empty.
function mergeSortedArrays(arr1, arr2): initialize mergedArray as empty list initialize pointer i to 0 for arr1 initialize pointer j to 0 for arr2 if arr1 is empty: return arr2 if arr2 is empty: return arr1 while i < len...