I have seen a lot of mergesort Python implementation and I came up with the following code. The general logic is working fine, but it is not returning the right results. How can I fix it?
Code:
def merge(left, right):temp = []i = 0j = 0while i < len(left) and j < len(right):if left[i] <= right[j]:temp.append(left[i])i = i + 1else:temp.append(right[j])j = j + 1print("i = ", i, "j = ", j)while i < len(left):temp.append(left[i])i += 1while j < len(right):temp.append(right[j])j += 1print("Returned from merge", temp)return tempdef mergesort(data):if len(data) < 2:returnleft = data[:len(data)//2]print(left)right = data[len(data)//2:]print(right)print("left only now")mergesort(left)print("right now")mergesort(right)return merge(left, right)data = mergesort([1, 20, 30, 25, 8, 7, 9])
In the main mergesort function I think the last line is not correct.