sorting - recursive merge sort in python -
i trying make merge sort using 2 functions in python. got error like
indexerror: list assignment index out of range whenever run code. don't know part wrong.
code below. appreciate!!
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 , 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
you can not assign value temp[k]
long element not exist.
delete row temp.append(99999)
, replace every temp[k]=a[i]
temp.append(a[i])
, every temp[k]=a[j]
temp.append(a[j])
.
you end with:
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 , 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 = [1,9,4,5] print(a) print(merge(a))
output:
[1, 9, 4, 5] [1, 4, 5, 9]
Comments
Post a Comment