I wrote a merge-sort algorithm in python. It works perfectly until 10000 numbers but after 10000 it gives me segmentation fault 11. What might be the problem? Any idea about it
def merge_count(arr):
if len(arr) < 2:
return (arr, 0)
m = int(len(arr) / 2)
left, l_counter = merge_count(arr[:m])
right, r_counter = merge_count(arr[m:])
return merge(left, right, l_counter + r_counter)
def merge(left, right, counter):
if len(left) * len(right) == 0:
return (left + right, counter)
if left[len(left) - 1] > right[len(right) - 1]:
val = left.pop(len(left) - 1)
counter += len(right)
else:
val = right.pop(len(right) - 1)
arr, counter = merge(left, right, counter)
return (arr + [val], counter)
It looks like you have a stack overflow. merge
uses stack space on the order of the size of the lists to merge, which is way more than Python can handle. Ordinarily, Python would stop you with a RuntimeError
before you got to that point; you probably used sys.setrecursionlimit
to go past the safe limit. Stop using setrecursionlimit
, and rewrite merge
to not use recursion.
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.