I am trying to write merge sort and stuck here.
What is the problem here with my code? I am trying to implement it without referring any resources and unnecessarily writing this line since some dumb rule in Stackoverflow forces to me explain my code.
def merge_sort(A):
if len(A) <= 1:
return A
#split list in 2
mid = len(A)/2
B = A[:mid]
C = A[mid:]
B = merge_sort(B)
C = merge_sort(C)
#merge
result = []
while len(B) > 0 and len(C) > 0:
if B[0] > C[0]:
result.append(C.pop(0))
else:
result.append(B.pop(0))
if len(B) > 0:
result.extend(merge_sort(B))
else:
result.extend(merge_sort(C))
print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
I get this error:
Traceback (most recent call last):
File "merge_sort.py", line 31, in <module>
print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
File "merge_sort.py", line 11, in merge_sort
B = merge_sort(B)
File "merge_sort.py", line 16, in merge_sort
while len(B) > 0 and len(C) > 0:
TypeError: object of type 'NoneType' has no len()
You merge_sort() function needs to
at the end but it does not. Functions return None by default and this is why you get the error.