我编写了以下合并排序代码:
def merge_sort(self,a):
#console.log(len(a))
if len(a) <= 1:
return a
left = []
right = []
result = []
middle = int(len(a)/2)
print middle
left = a[:middle] #set left equal to the first half of a
right = a[middle:] #set right equal to the second half of a
print left
print right
left = self.merge_sort(left)
right = self.merge_sort(right)
result = self.merge(left, right)
return result
然后合并代码:
def merge(self, left, right):
result = []
while len(left) > 0 or len(right) > 0:
if len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
result.append(left[0])
left = left.pop(1) #remove the first element from left
elif len(left) > 0:
result.append(left[0])
left = left.pop(1) #remove the first element from left
elif len(right) > 0:
result.append(right[0])
right = right.pop(1) #remove the first element from right
else:
result.append(right[0])
right = right.pop(1)
return result
我将数组发送给它:a = [12,0,232]
我得到以下输出(不同的迭代),在最后一个输出中我得到了错误,请帮助我不明白为什么会出现错误,谢谢!:
(1 [12] [0, 232]) (1 [0] [232])
Traceback (last recent call last): ...\Sort_Class.py", line 116, in merge left = left.pop(1) #remove the first element from left IndexError: pop index out of range