谁会知道为什么我的就地合并排序是“索引超出范围” ?
最初,我的“ low”值为0,但是我决定对每个“ low,mid,high”值执行+1,以补偿索引空间。谁能找到任何东西?谢谢。
def merge(array, low, mid, high):
i,j,k = low,mid+1,low
leftarray = array[low:mid+1]
rightarray = array[mid+1:high+1]
temp= [0]*high
while i<=mid and j<=high:
if array[i]<array[j]:
temp[k] = array[i]
i+=1
else:
temp[k] = array[j]
j+=1
k+=1
if i>mid:
temp[k:high+1] = array[j:high+1]
else:
temp[k:high+1] = array[i:mid+1]
array[low:high+1] = temp[low:high+1]
def inplace(array,low,high):
if low<high:
mid = int((low+high)/2)
inplace(array,low,mid)
inplace(array,mid+1,high)
merge_test(array,low,mid,high)
array = [20,30,21,15,42,45,31,0,9]
inplace(array, 0, len(array)-1)
print(array)
答案 0 :(得分:2)
if i>mid:
temp[k:high+1] = array[j:high+1]
else:
temp[k:high+1] = array[i:mid+1]
array[low:high+1] = temp[low:high+1]
def merge_test(array, low, mid, high):
i,j,k = low,mid+1,low
leftarray = array[low:mid+1]
rightarray = array[mid+1:high+1]
temp= [0]*high
while i<=mid and j<=high:
if array[i]<array[j]:
temp[k] = array[i]
i+=1
else:
temp[k] = array[j]
j+=1
k+=1
if i>mid:
temp[k:high+1] = array[j:high+1]
else:
temp[k:high+1] = array[i:mid+1]
array[low:high+1] = temp[low:high+1]
def inplace(array,low,high):
if low<high:
mid = int((low+high)/2)
inplace(array,low,mid)
inplace(array,mid+1,high)
merge_test(array,low,mid,high)
array = [20,30,21,15,42,45,31,0,9]
inplace(array, 0, len(array)-1)
print(array)
输出:
[0, 9, 15, 20, 21, 30, 31, 42, 45]
PS:请始终发布完整的错误堆栈跟踪。它有助于调试代码。您还应该尝试读取堆栈跟踪。