Inputs are two sorted lists (of the same length) of numbers. I would like to return a new merged, sorted new list. I have written the following code, but most lines are used to deal with the end case. I am wondering if there is any better way to write it.
def merge(array1,array2):
result = [0]*len(array1)*2
i = 0 # left index
j = 0 # right index
for k in range(0,len(result)):
# when none of the pointer is at the end of the list
if i != len(array1)-1 and j != len(array2)-1:
if array1[i] < array2[j]:
result[k] = array1[i]
i = i + 1
elif array1[i] > array2[j]:
result[k] = array2[j]
j = j + 1
# the following codes are used to deal with the end cases.
# possible to write it more compactly?
elif i == len(array1)-1:
if j > len(array2)-1:
result[-1] = array1[-1]
return result
elif array1[i] < array2[j]:
result[k] = array1[i]
result[k+1:] = array2[j:]
return result
else:
result[k] = array2[j]
j = j + 1
elif j == len(array2)-1:
if i > len(array1)-1:
result[-1] = array2[-1]
elif array2[j] < array1[i]:
result[k] = array2[j]
result[(k+1):] = array1[i:]
return result
else:
result[k] = array1[i]
i = i + 1
return result
extend
orsorted
? \$\endgroup\$reinventing-the-wheel
to your question, otherwise everyone is just going to tell you the same thing. \$\endgroup\$