I'm trying to implement simple merge sort algorithm in Python.
arr=[1,3,5,2,4,6]
n=6
l=0
h=n-1
def merge_Sort(l,h):
if(l==h):
return arr[l]
m=(h+l)//2
arr1=merge_Sort(l,m)
arr2=merge_Sort(m+1,h)
s1=m-l
s2=h-(m+1)
mer=[]
k1=k2=0
while(k1<=s1 or k2<=s2):
if(arr1[k1] < arr2[k2]):
mer.append(arr1[k1])
k1+=1
else:
mer.append(arr2[k2])
k2+=1
if(k1>s1):
while(k2<=s2):
mer.append(arr2[k2])
k2+=1
if(k2>s2):
while(k1<=s1):
mer.append(arr1[k1])
k1+=1
return mer
res=merge_Sort(l,h)
print(res)
But I'm getting this error message when running the above code:
TypeError: 'int' object is not subscriptable
Can anybody explain to me why I'm geting this error?
The problems are here:
if(l==h):
return arr[l]
...
while(k1<=s1 or k2<=s2):
Use this code instead:
if(l==h):
return arr[l:l+1]
...
while(k1<=s1 and k2<=s2):
Side note, this piece of code:
if(k1>s1):
while(k2<=s2):
mer.append(arr2[k2])
k2+=1
if(k2>s2):
while(k1<=s1):
mer.append(arr1[k1])
k1+=1
can be simplified to this:
mer.extend(arr1[k1:s1+1])
mer.extend(arr2[k2:s2+1])
Change this:
if(l==h):
return arr[l]
into:
if(l==h):
return [arr[l]]
and this:
while(k1<=s1 or k2<=s2):
into:
while(k1<=s1 and k2<=s2):
I tested it and it works fine.
TypeError: 'int' object is not subscriptable
means you're trying to iterate (or use something like a[0]
) over int
.
Add this before the "crash line".
print(arr1, arr2)
Output: 1 3
So you're doing 3[k2]
.
an alternative method would be :
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)
def merge(left,right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
This would be a relatively standard method:
def merge(left, right):
res = []
while len(left) > 0 and len(right) > 0:
if left[0] <= right[0]:
res.append(left[0])
left.pop(0)
else:
res.append(right[0])
right.pop(0)
while len(left) > 0:
res.append(left[0])
left.pop(0)
while len(right) > 0:
res.append(right[0])
right.pop(0)
return res
def merge_sort(lst):
if len(lst) <= 1:
return lst
left = lst[:(len(lst)//2)]
right = lst[(len(lst)//2):]
left = merge_sort(left)
right = merge_sort(right)
return merge(left,right)
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.