The question is :
Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list, without using the inbuilt sort function
I tried :
list1=(input("Enter the elements of list :")).split()
list2=(input("Enter the elements of list :")).split()
merged_list,sorted_list=(list1+list2),[]
#Without using sort()method
def merge(list1,list2):
global merged_list,sorted_list
if len(merged_list)==0 : return sorted_list
sorted_list.append(min(merged_list))
merged_list.remove(min(merged_list))
merge(list1,list2)
print(merge(list1,list2))
This gives output as "None", I don't know why. Also, it works well for alphabetic strings, but doesn't work for numerics, For example, if you give [02,1,0123] ,it returns [0123,02,1]. What should I change to make it work for both strings and numbers?
This isn't exactly what you are asking, but I'll add this as an example of:
:
def merge(list1,list2):
# base case: one or both are empty lists
if len(list1) == 0 or len(list2) == 0:
return list1 + list2
if list1[0] < list2[0]:
return [list1[0]] + merge(list1[1:], list2)
else:
return [list2[0]] + merge(list1, list2[1:])
list1 = [1, 4, 6, 8, 14, 22]
list2 = [1, 2, 5, 9, 10, 15, 18, 20]
merge(list1,list2)
# [1, 1, 2, 4, 5, 6, 8, 9, 10, 14, 15, 18, 20, 22]