Merge Sort divides the array(or given data structure) into two halves, and again calls itself recursively until single element is left and then merges the two sorted halves. It requires a temporary array to merge and store the sorted array.
This algorithm falls under Divide & Conquer Technique which is divides the problem, finds the solution to smaller problem and then merges these to get the solution to the original problem. Let's look at the working of this algorithm.
Do refer the code available the end of this section to understand the following theory.
PS: We give random inputs because the no. of input will generally be 100 or 1000 to find the time complexity and manually giving so many inputs is cumbersome work.
There exists two recursive calls in which the elements gets halved in each call. And the transfer of elements from arr->temp and at last from temp->arr will effect the time complexity. So declare a global variable count, increment this variable in all the loops present in the merge function (within the loops at step 3.2, 3.3, 3.4 & 3.5 in the above working procedure).
Time Complexity: O(nlog(n))
Please open this in your pc or with a compatible app in your mobile.
C++ Implementation for MERGE SORTThat's it from this blog post. If you liked it then do share this blog with your friends or people who wanna get into programming world. Thank You!