Array ( [0] => [1] => questions [2] => Popular-Algorithms [3] => Merge-Sort ) Popular Algorithms | Merge Sort | THE INQUISITIVE





Merge Sort

LEVEL:Beginner

Description

Given a list of integers and a integer (size of array). Sort the given array using Merge Sort Algorithm.

Input Format

First line contains the size of array (n) followed by n integers separated by spaces.

Output Format

Print the sorted array separated by spaces.


Example 1:

Input
5
32 12 4 64 100
Output
4 12 32 64 100
Example 2:

Input
6
96 54 100 32 45 64
Output
32 45 54 64 96 100
Example 3:

Input
6
69 95 343 455 62 44
Output
44 62 69 95 343 455

oops

Login to see Discussion




Approach

Step-i) if it is only one element in the list it is already sorted, return.
Step-ii) divide the list recursively into two halves until it can no more be divided.
Step-iii) merge the smaller lists into new list in sorted order.

Time Complexity: O(n*Log n)
Space Complexity: O(n)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution