In this workshop: Implement the Merge Sort Algorithm, I completed the task but I do not know how recursive function worked here.
Full code:
def merge_sort(array):
if len(array) <= 1:
return
middle_point = len(array) // 2
left_part = array[:middle_point]
right_part = array[middle_point:]
merge_sort(left_part)
merge_sort(right_part)
left_array_index = 0
right_array_index = 0
sorted_index = 0
while left_array_index < len(left_part) and right_array_index < len(right_part):
if left_part[left_array_index] < right_part[right_array_index]:
array[sorted_index] = left_part[left_array_index]
left_array_index += 1
else:
array[sorted_index] = right_part[right_array_index]
right_array_index += 1
sorted_index += 1
while left_array_index < len(left_part):
array[sorted_index] = left_part[left_array_index]
left_array_index += 1
sorted_index += 1
while right_array_index < len(right_part):
array[sorted_index] = right_part[right_array_index]
right_array_index += 1
sorted_index += 1
if __name__ == '__main__':
numbers = [4, 10, 6, 14, 2, 1, 8, 5]
print('Unsorted array: ')
print(numbers)
merge_sort(numbers)
print('Sorted array: ')
print(numbers)
Although -for me - recursive functions like Fibonacci are understandable, my problem here is that, I cannot relate this one to the recursive ones I did during the course.
merge_sort(left_part)
merge_sort(right_part)
Is there an intuitive way to understand it? I guess some print() functions may prove the job of this code. However, I wanna learn it so that I can make the best use of them in my future codes. So understanding it deeply and intuitively is what I need.
Thanks for any help.