📅  最后修改于: 2023-12-03 14:50:48.202000             🧑  作者: Mango
This is a programming question from the ISRO CS 2018 exam. The problem statement is as follows:
You are given a list of n
integers. Write a program to sort the list using the merge sort algorithm.
The input consists of:
n
indicating the number of elements in the list.n
space-separated integers.The program should output the sorted list of integers in a single line, separated by a space.
5
3 1 4 2 5
1 2 3 4 5
To sort the list using the merge sort algorithm, we will divide the list into two halves recursively until we get sub-lists that have only one element. We will then merge the sub-lists by comparing their first elements and appending the smaller element to the result list. We will repeat this process until all sub-lists are merged into a single sorted list.
Here is the code in Python:
def merge_sort(lst):
if len(lst) <= 1:
return lst
mid = len(lst) // 2
left = lst[:mid]
right = lst[mid:]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
n = int(input())
lst = list(map(int, input().split()))
sorted_lst = merge_sort(lst)
print(*sorted_lst)
The merge_sort
function takes a list as input and sorts it using the merge sort algorithm. The merge
function merges two sorted lists and returns the sorted result.
We read the input from the user using the input
function and convert it into a list of integers using the map
function. We then call the merge_sort
function with the list as input and output the sorted list using the print
function. We use the *
operator to unpack the list and print the integers separated by a space.