Sobes.tech
Senior

Task 2. Merging two sorted arrays Given two sorted arrays in ascending order, nums1 and nums2. It is necessary to merge them into one sorted array in ascending order. nums1 = [1, 3, 5] nums2 = [2, 4, 6] merge_sorted(nums1, nums2) -> [1, 2, 3, 4, 5, 6]

sobes.tech AI

Answer from AI

To merge two sorted arrays, you can use two pointers that traverse the arrays and compare the current elements, adding the smaller one to the resulting array. This is a classic merging algorithm that works in O(n + m) time, where n and m are the sizes of the arrays.

Example in Python:

def merge_sorted(nums1, nums2):
    i, j = 0, 0
    merged = []
    while i < len(nums1) and j < len(nums2):
        if nums1[i] < nums2[j]:
            merged.append(nums1[i])
            i += 1
        else:
            merged.append(nums2[j])
            j += 1
    # Add remaining elements
    merged.extend(nums1[i:])
    merged.extend(nums2[j:])
    return merged

# Usage example
nums1 = [1, 3, 5]
nums2 = [2, 4, 6]
print(merge_sorted(nums1, nums2))  # [1, 2, 3, 4, 5, 6]
Task 2. Merging two sorted arrays Given two sorted… - sobes.tech