I’m practicing merge sort with an exercise from a Youtube tutorial, this is it.
Im just doing the ‘descending = false’ version.
So at first I tried to solve it on my own by editing a block of code of merge sort that works for a list of numbers.
def merge_sort(arr, key, descending=False):
if len(arr) <= 1:
return arr
mid = len(arr)//2
left_list = merge_sort(arr[0:len(arr) // 2], key)
right_list = merge_sort(arr[len(arr) // 2:], key)
sorted_list = merge_two_sorted_lists(left_list, right_list)
return sorted_list
def merge_two_sorted_lists(a,b):
merged = []
len_a = len(a)
len_b = len(b)
i = j = k = 0
while i < len_a and j < len_b:
if a[i]['time_hours'] <= b[j]['time_hours']:
merged.append(a[i])
i+=1
else:
merged.append(b[j])
j+=1
k+=1
while i < len_a:
merged.append(a[i])
i+=1
k+=1
while j < len_b:
merged.append(b[j])
j+=1
k+=1
return merged
if __name__ == '__main__':
arr = [
{'name': 'rajab', 'age': 12, 'time_hours': 3},
{'name': 'vignesh', 'age': 21, 'time_hours': 2.5},
{'name': 'chinmay', 'age': 24, 'time_hours': 1.5},
{'name': 'vedanth', 'age': 17, 'time_hours': 1},
]
new_list = merge_sort(arr, key='time_hours', descending=True)
print(new_list)
But it didn’t work, here is the output of it
[{'name': 'vedanth', 'age': 17, 'time_hours': 1}, {'name': 'chinmay', 'age': 24, 'time_hours': 1.5}, {'name': 'vignesh', 'age': 21, 'time_hours': 2.5}, {'name': 'rajab', 'age': 12, 'time_hours': 3}]
So I looked at the solution and made some changes on the first ‘merge_sort’ function.
def merge_sort(arr, key, descending=False):
if len(arr) <= 1:
return arr
mid = len(arr)//2
left_list = merge_sort(arr[0:len(arr) // 2], key)
right_list = merge_sort(arr[len(arr) // 2:], key)
sorted_list = merge_two_sorted_lists(left_list, right_list)
return sorted_list
It worked, but I have no idea how, I tried to debug it several times but still cannot understand why returning some values back made it work. So, I will be delighted if someone explains why I need to return the list when dividing it?