次のマージソートコードを書きました:
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])
トレースバック (最新の呼び出しは最後): ...\Sort_Class.py"、116 行目、マージ中 left = left.pop(1) #左から最初の要素を削除 IndexError: 範囲外のインデックスをポップ