def merge_sorted_arrays(arr1, arr2):
"""
Merge two sorted arrays into one sorted array.
Args:
arr1: First sorted array
arr2: Second sorted array
Returns:
A new sorted array containing all elements from both input arrays
"""
# Initialize pointers for both arrays
i, j = 0, 0
merged = []
# Compare elements and add the smaller one to the result
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# Add remaining elements from arr1 (if any)
while i < len(arr1):
merged.append(arr1[i])
i += 1
# Add remaining elements from arr2 (if any)
while j < len(arr2):
merged.append(arr2[j])
j += 1
return merged
# Example usage:
array1 = [1, 3, 5, 7]
array2 = [2, 4, 6, 8, 9]
result = merge_sorted_arrays(array1, array2)
print(result) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The algorithm works by maintaining two pointers, one for each array, and comparing the elements at those positions. It always takes the smaller element and advances the corresponding pointer. Once one array is exhausted, it appends all remaining elements from the other array.