arrays - Why doesn't this python implementation of mergesort work? -
when input [8,7,6,5,4,3,2,1]
output => [4, 3, 2, 1, 8, 7, 6, 5]
.
it seems thing different working solution (comparing here) instead of sorted
list, have k
variable incrementing, , update arr[k]
in place of sorted
.
why doesn't work? , how updating arr[k]
work? seems losing data updating original input array.
def mergesort(arr): if len(arr) == 1: return else: mid = len(arr)/2 left = arr[0:mid] right = arr[mid:len(arr)] sorted = [] = 0 j = 0 mergesort(left) mergesort(right) while < len(left) , j < len(right): if left[i] < right[j]: sorted.append(left[i]) += 1 else: sorted.append(right[j]) j += 1 while < len(left): sorted.append(left[i]) += 1 while j < len(right): sorted.append(right[j]) j += 1 return sorted
you should assign left , right variable function return sorted list after sorting in base case should return list , use //
integer division check code
def mergesort(arr): if len(arr) == 1: return arr else: mid = len(arr)//2 left = arr[0:mid] right = arr[mid:len(arr)] sorted = [] = 0 j = 0 left = mergesort(left) #left sorted right = mergesort(right) while < len(left) , j < len(right): if left[i] < right[j]: sorted.append(left[i]) += 1 else: sorted.append(right[j]) j += 1 while < len(left): sorted.append(left[i]) += 1 while j < len(right): sorted.append(right[j]) j += 1 return sorted print (mergesort([8,7,6,5,4,3,2,1,3]))
Comments
Post a Comment