Question: Chapter 5 - Programming Project: Implement a function that takes in two sorted lists and merges them into one list, the new list must be

Chapter 5-Programming Project: Implement a function that takes in two sorted lists and merges them into one list, the new list must be sorted. The function MUST run in O(m+n), where m is the length of list 1 and n the length of list 2. In other words, the function cannot do more than one pass on list 1 and list 2.
Use the base code given and write it in python:
# Assignment: Programming Project 3
def merge_sorted_lists(list1, list2):
"""
This function merges two sorted lists into one sorted list.
Parameters:
list1(list): The first sorted list.
list2(list): The second sorted list.
Returns:
list: A sorted list that contains all elements from list1 and list2.
"""
merged_list =[]
# WRITE YOUR CODE HERE
# Hint:
# 1. Keep two pointers, each initially pointing to the start of list1 and list2.
# 2. Compare the elements pointed by the pointers and choose the smaller one to append to the 'merged_list'.
# 3. Increment the pointer of the list from which an element is chosen.
# 4. If one list gets exhausted, append all remaining elements from the other list to 'merged_list'.
return merged_list
if __name__=='__main__':
list1=[1,3,5,7,9]
list2=[2,4,6,8,10]
print(merge_sorted_lists(list1, list2)) # [1,2,3,4,5,6,7,8,9,10]
list3=[1,3,5,7]
list4=[2,4,6,8,9,10]
print(merge_sorted_lists(list3, list4)) # [1,2,3,4,5,6,7,8,9,10]

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!