📌  相关文章
📜  国际空间研究组织 | ISRO CS 2018 |问题 10(1)

📅  最后修改于: 2023-12-03 14:50:48.202000             🧑  作者: Mango

ISRO CS 2018 Questions | Problem 10

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.

Problem Input

The input consists of:

  • The first line contains a single integer n indicating the number of elements in the list.
  • The second line contains n space-separated integers.
Problem Output

The program should output the sorted list of integers in a single line, separated by a space.

Sample Input
5
3 1 4 2 5
Sample Output
1 2 3 4 5
Approach

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.

Code

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.