Algorithm:
- Create a new array
merged
of sizem.length + n.length
to store the merged sorted array. - Initialize three pointers
i
,j
, andk
.i
andj
will point to the first elements of the arraysm
andn
, respectively.k
will point to the first element of the arraymerged
. - While
i
is less than the length ofm
andj
is less than the length ofn
:- If the element at
i
inm
is less than or equal to the element atj
inn
:- Copy the element at
i
inm
to the element atk
inmerged
. - Increment
i
andk
.
- Copy the element at
- Otherwise:
- Copy the element at
j
inn
to the element atk
inmerged
. - Increment
j
andk
.
- Copy the element at
- If the element at
- While
i
is less than the length ofm
:- Copy the element at
i
inm
to the element atk
inmerged
. - Increment
i
andk
.
- Copy the element at
- While
j
is less than the length ofn
:- Copy the element at
j
inn
to the element atk
inmerged
. - Increment
j
andk
.
- Copy the element at
- Calculate the middle index of the array
merged
. - If the length of the array
merged
is even:- Return the average of the two elements at the middle index and the middle index minus one.
- Otherwise:
- Return the element at the middle index.
Time complexity: O(m + n), where m and n are the lengths of the arrays m
and n
, respectively. This is because we only need to iterate over the two arrays once.
Space complexity: O(m + n), where m and n are the lengths of the arrays m
and n
, respectively. This is because we need to store the merged array merged
.
for example, consider the following two arrays:
m = [1, 3, 5, 7] n = [2, 4, 6, 8]
The merged array will be:
merged = [1, 2, 3, 4, 5, 6, 7, 8]
The middle index of the merged array is 3. Therefore, the function will return the average of the two elements at index 3 and index 2, which is (3 + 4) / 2 = 3.5
.