This is Merge Sort that i implemented, i feel i can make it better esp the combination function.
So i split the code into functions because i don't like seeing a bunch of spaghetti code in a single function. I have the combination logic which combines the left and right array such lower elements go first.
def combine(left:list, right:list): #Combines both paths left.append(float('inf')) #So the Array is never empty right.append(float('inf')) #and the final element to compare is large combined_list =  while len(left) !=1 or len(right) != 1: if left < right: combined_list.append(left.pop(0)) else: combined_list.append(right.pop(0)) return combined_list
Next i have this recursive function which calls itself and combination logic then after reducing the array into singular pieces then returns the bigger sorted chunks and hence final array is hence sorted.
def merge_sort(array:list): half_length = len(array)//2 left = array[:half_length] right = array[half_length:] if len(left) > 1: left = merge_sort(left) if len(right) > 1: right = merge_sort(right) return combine(left, right) print(merge_sort([1,2,8,5,2,4,6,9,4,2]))
I feel that
left.append(float('inf')) is a hack around, is there a better way of doing it spiting it into functions.