Merge Sort follows the rule of Divide and Conquer to sort a given set of numbers/elements, recursively, hence consuming less time.
In the last two tutorials, we learned about Selection Sort and Insertion Sort, both of which have a worst-case running time of O(n2). As the size of input grows, insertion and selection sort can take a long time to run.
Merge sort, on the other hand, runs in O(n*log n) time in all the cases.
Before jumping on to, how merge sort works and its implementation, first lets understand what is the rule of Divide and Conquer?
The concept of Divide and Conquer involves three steps:
- Divide the problem into multiple small problems.
- Conquer the sub problems by solving them. The idea is to break down the problem into atomic sub problems, where they are actually solved.
- Combine the solutions of the sub problems to find the solution of the actual problem.
How Merge Sort Works?
To understand merge sort, we take an unsorted array as the following
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two arrays into halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
Now, we combine them in exactly the same manner as they were broken down. Please note the color codes given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first, followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in a sorted order.
After the final merging, the list should look like this
Now we should learn some programming aspects of merge sorting.
Below, we have a pictorial representation of how merge sort will sort the given array.