I have two sorted arrays
array1 = [0, 3, 4, 31]
array2 = [4, 6, 30]
I try to sort these arrays by using the code below:
def mergeSortedArray(array1, array2):
if not len(array1):
return array2
if not len(array2):
return array1
mergedArray = []
array1Item = array1[0]
array2Item = array2[0]
i = 0
j = 0
while (i < len(array1)) and (j < len(array2)):
if array1Item < array2Item:
mergedArray.append(array1Item)
array1Item = array1[i + 1]
i += 1
else:
mergedArray.append(array2Item)
print(j)
array2Item = array2[j + 1]
j += 1
return mergedArray
print(mergeSortedArray([0, 3, 4, 31], [4, 6, 30]))
But the terminal keep telling me that:
line 26, in mergeSortedArray
array2Item = array2[j + 1]
IndexError: list index out of range
I wonder which part I did wrong! Can someone explain to me? plz~
BTW, what is the syntactically cleanest way to accomplish this?
while i < len(array1)but then you referencearray1[i+1]. Just tryarray1[len(array1)+1]index is inherently more than length of your list. The index of lists in python starts at 0.