sorting - RunTimeError in merge sort function using python -
i trying write merge sort function using python 2 runtimeerror
input: unsorted list (ex:[10,9,8,7,6,5,4,3,2,1])
output: [1,2,3,4,5,6,7,8,9,10]
my code shown below:
lst = [10,9,8,7,6,5,4,3,2,1] def mergesort(array): if len(array) == 1: return array left = [] right = [] in array: if <= len(array)/2: left.append(i) else: right.append(i) left = mergesort(left) right = mergesort(right) return merge(left,right) def merge(left,right): sortedlist= [] while left , right: if left[0]>right[0]: sortedlist.append(right[0]) right.pop(0) else: sortedlist.append(left[0]) left.pop(0) while left: sortedlist.append(left[0]) left.pop(0) while right: sortedlist.append(right[0]) right.pop(0) return sortedlist print mergesort(lst)
the runtimeerror is: maximum recursion depth exceeded
. know cause of error?
you're comparing list values list indices:
for in array: # list value if <= len(array)/2: # len(array)/2 list index
change if <= array[len(array)/2]:
, should work.
Comments
Post a Comment