would anyone know why my in place merge sort is "index out of range" ?
I originally had my "low" at 0 but decided to do a +1 for each "low,mid,high" to compensate for index space. Can anyone find anything? Thanks.
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)
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)
output :
[0, 9, 15, 20, 21, 30, 31, 42, 45]
PS: please always post full error stack trace. It helps debugging code. You should also try reading stack trace.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.