Learner Level

Implement the mergeSortedArrayInPlaceResult method that merges two sorted arrays into a sorted result.

The input contains two already sorted integer arrays, a and b, along with their sizes sizeA and sizeB. Your task is to merge both arrays into one sorted array.

The returned array should contain all values from both arrays in ascending order. Empty input arrays should also be handled correctly.

For example, merging [1,3,5] and [2,4] should return [1,2,3,4,5].

Example 1
Input:
a (int[]) = [1,3,5]
sizeA (int) = 3
b (int[]) = [2,4]
sizeB (int) = 2
Return:
(int[]) [1,2,3,4,5]
Example 2
Input:
a (int[]) = [1,2,3]
sizeA (int) = 3
b (int[]) = [4,5]
sizeB (int) = 2
Return:
(int[]) [1,2,3,4,5]
Example 3
Input:
a (int[]) = []
sizeA (int) = 0
b (int[]) = [1]
sizeB (int) = 1
Return:
(int[]) [1]

Use two pointers, one for each sorted array.

Compare the current values from both arrays. Add the smaller value to the result and move that array pointer forward. This keeps the result sorted without sorting again.

After one array is fully processed, copy the remaining values from the other array because they are already sorted.

Pseudocode:

function mergeSortedArrayInPlaceResult(a, sizeA, b, sizeB):
    i = 0
    j = 0
    result = empty array
    while i < sizeA and j < sizeB:
        if a[i] <= b[j]:
            append a[i] to result
            i++
        else:
            append b[j] to result
            j++
    while i < sizeA:
        append a[i] to result
        i++
    while j < sizeB:
        append b[j] to result
        j++
    return result
Run your code to see the result.