I'm relatively new to Python.
I'm trying to implement merge sort in python. However, a test case like [1, 2, 6, 4, 5] came out to be [1, 1, 1, 1, 1] when "sorted." After a long time, I found the cause to be in the merge algorithm. The actual algorithm looked fine, except I don't know why a certain part isn't working.
def merge(arr, left, right, start_pos):
i = 0
j = 0
k = start_pos
while i < len(left) or j < len(right):
if i >= len(left):
arr[k] = right[j] # This assignment has no effect
j += 1
k += 1
elif j >= len(right):
arr[k] = left[i] # Same here
i += 1
k += 1
else:
if arr[i] < arr[j]:
arr[k] = arr[i] # Here
i += 1
k += 1
else:
arr[k] = arr[j] # And here
j += 1
k += 1
First of all, the goal was to be given an array called arr, and array called left, an array called right, and an int called start_pos, the merge algorithm replaces the values in arr starting at start_pos with left and right merged. However, as you can see in the comments, for some reason the assigment isn't working. I couldn't seem to figure out why. It probably won't be that much help, but just in case here is the whole code:
def merge_sort(arr):
merge_sort_helper(arr, 0, len(arr))
def merge_sort_helper(arr, left, right):
if left >= right - 1:
return
mid = int((left + right) / 2)
merge_sort_helper(arr, left, mid)
merge_sort_helper(arr, mid, right)
merge(arr, arr[left : mid], arr[mid : right], left)
def merge(arr, left, right, start_pos):
i = 0
j = 0
k = start_pos
while i < len(left) or j < len(right):
if i >= len(left):
arr[k] = right[j]
j += 1
k += 1
elif j >= len(right):
arr[k] = left[i]
i += 1
k += 1
else:
if arr[i] < arr[j]:
arr[k] = arr[i]
i += 1
k += 1
else:
arr[k] = arr[j]
j += 1
k += 1
printcommands to show what is actually happening as you work through the sort. I can't see that the assignment isn't working, because you neglected to show us.