我寫以下合併排序代碼:IndexError:彈出索引超出範圍(蟒)
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
我發送的數組: 一個= [ 12,0,232]
我得到以下輸出(不同的迭代),並在最後輸出我得到的錯誤,請幫助我不明白爲什麼錯誤在那裏謝謝你!:
(1 [12] [0,232]) (1 [0] [232])
回溯(最近最後調用): ... \ Sort_Class.py」 ,第116行,合併 left = left.pop(1)#從左邊移除第一個元素 IndexError:彈出索引超出範圍
如果'left'比2項短,那麼你會得到這個錯誤。 –