[英]recursive merge sort in python
我正在嘗試使用python中的兩個函數進行合並排序。 但是我有一個錯誤
IndexError:只要運行我的代碼, 列表分配索引就會超出范圍 。 我不知道哪一部分錯了。
這是我的下面的代碼。 任何幫助將不勝感激!
def merge(A):
def merge_sort(A,first,last):
if first<last:
mid=(first+last)//2
merge_sort(A,first, mid)
merge_sort(A,mid+1,last)
temp=[]
temp.append(99999)
i=first
j=mid+1
k=0
while i<=mid and j<=last:
if A[i]<=A[j]:
temp[k]=A[i]
k=k+1
i=i+1
else:
temp[k]=A[j]
k=k+1
j=j+1
while i<=mid:
temp[k]=A[i]
k=k+1
i=i+1
while j<=last:
temp[k]=A[j]
k=k+1
j=j+1
a=0
b=first
while a<k:
A[b]=temp[a]
b=b+1
a=a+1
merge_sort(A,0,len(A)-1)
return A
只要此元素不存在,就不能為temp[k]
分配值。
刪除行temp.append(99999)
,將每個temp[k]=A[i]
temp.append(A[i])
,將每個temp[k]=A[j]
temp.append(A[j])
。
您最終將得到:
def merge(A):
def merge_sort(A,first,last):
if first<last:
mid=(first+last)//2
merge_sort(A,first, mid)
merge_sort(A,mid+1,last)
temp=[]
i=first
j=mid+1
k=0
while i<=mid and j<=last:
if A[i]<=A[j]:
temp.append(A[i])
k=k+1
i=i+1
else:
temp.append(A[j])
k=k+1
j=j+1
while i<=mid:
temp.append(A[i])
k=k+1
i=i+1
while j<=last:
temp.append(A[j])
k=k+1
j=j+1
a=0
b=first
while a<k:
A[b]=temp[a]
b=b+1
a=a+1
merge_sort(A,0,len(A)-1)
return A
A = [1,9,4,5]
print(A)
print(merge(A))
輸出:
[1, 9, 4, 5]
[1, 4, 5, 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.