Medium

# 2. Merge Sort - Updated - Most Efficient ways to Implement

Objective : Write Merge Sort algorithm to sort elements in an array

Input: A unsorted array, arrA[].

Output : A sorted array.

Approach:

Divide and Conquer: In this approach we divide the main problems into smaller problems, solve them and merge the results to get the final result.

How Divide and conquer works in Merge Sort:

We divide the elements into two half’s by middle of the array. We solve the left half and right half recursively and merge the results.

Merging:

Once the sorting is done individually on both the half’s, our next task will be merge them. To merge we start with both the arrays at the beginning, pick the smaller one put into array and then compare the next elements and so on.

Time Complexity : O(nlogn) { O(logn) for dividing and O(n) for merging.

Note: we can make merging more efficient by implementing these approaches

Using Auxiliary Array with copying data – In this approach you wont create new array everytime for merging instead you create Auxiliary array. This will save memory for you.
Alternate Merging Between Primary and Auxiliary Array: This is the best approach for merging. You don’t copy the entire array to auxiliary array for merging instead you do alternate merging between main array and auxiliary array.

`Below is the running time comparison between all three approaches`

You can find the implementation of all these approaches here –

Output :
1 2 3 4 5 6 9 10