I implemented such merge sorting algorithm, hoverer I got some issues
import sys
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
a = data[1:]
print(merge_sort(a))
def merge(left,rigt):
result = []
i = j = 0
while i < len(left) and j < len(rigt):
if left[i] <= rigt[j]:
result.append(left[i])
i += 1
else:
result.append(rigt[j])
j += 1
result += left[i:]
result += rigt[j:]
return result
def merge_sort(a):
if len(a) <= 2:
return 1
middle = len(a)//2
left = a[:middle]
right = a[middle:]
left = merge_sort(left)
right = merge_sort(right)
return list(merge(left,right))
I got such error
TypeError: object of type 'int' has no len()
I can't understand, where I went wrong, why program thinks that "left" and "right" are int, however it is array.
You should replace
if len(a) <= 2:
return 1
with
if len(a) == 1:
return a
to return a list which is not partitionable.
您忘记了merge_sort函数的终止情况,该情况返回1。因此,当递归到达底部时,left和rigt都为int,因此您需要在代码中加以考虑。
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.