0% found this document useful (0 votes)
4 views1 page

DA-1

The document provides a Python script that merges two sorted input lists into a single sorted list without using built-in sorting functions. It defines a function to compare elements from both lists and append them to a new list in sorted order. The script prompts the user for two sorted lists and displays the merged result.

Uploaded by

nopeynope0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

DA-1

The document provides a Python script that merges two sorted input lists into a single sorted list without using built-in sorting functions. It defines a function to compare elements from both lists and append them to a new list in sorted order. The script prompts the user for two sorted lists and displays the merged result.

Uploaded by

nopeynope0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Write a python script to accept two input lists in sorted order and create a new

list which combines both lists in sorted order and display it. Avoid using
builtin functions for sorting.

Input format

Get list1

Get list 2

Output format

Display the merged sorted list

For example:

Input Result
[1, 5, 8, 14, 16]
[2, 4, 6, 9, 11]
[1, 2, 4, 5, 6, 8, 9, 11, 14, 16]
[11, 14, 19, 23, 25]
[3, 17, 22, 27]
[3, 11, 14, 17, 19, 22, 23, 25, 27]

Answer:

def merge_sorted_lists(list1, list2):


merged_list = []
i = 0
j = 0

while i < len(list1) and j < len(list2):


if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1

# Add remaining elements from list1


while i < len(list1):
merged_list.append(list1[i])
i += 1

# Add remaining elements from list2


while j < len(list2):
merged_list.append(list2[j])
j += 1

return merged_list

# Get input lists


list1 = [int(x) for x in input("Enter list 1 in sorted order: ").split()]
list2 = [int(x) for x in input("Enter list 2 in sorted order: ").split()]

# Merge and sort lists


merged_sorted_list = merge_sorted_lists(list1, list2)

# Display the merged sorted list


print("Merged sorted list:", merged_sorted_list)

You might also like