This post is completed by 2 users

  • 1
Add to List

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.


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.


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.

Merge Sort
Merge Sort

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
Data SizeDynamic Memo Allocation AlgoUsing Auxillary Array with copying dataAlternate Merging Between Primary and Auxillary Array
1 Million600-630 mili sec450-470 mili sec400-425 mili sec
10 million6 secs4.2 secs2.3 secs
100 million56 secs46 sec18 sec

You can find the implementation of all these approaches here –

GitHub - Three Different Implementations of Merge Sorts

Output :
1 2 3 4 5 6 9 10