Merge sort is one of the most efficient sorting algorithms for larger amount of data. Merge Sort is quite fast, and has a time complexity of O(n*log n) . It is also a stable sort, which means the “equal” elements are ordered in the same order in the sorted list. In this section we will understand why the running time for merge sort is O(n*log n). Merge sort is in the group of divide and conquer algorithms, so it creates multiple sub-problems from a single problem.
As we have already discussed that merge sort utilizes divide-and-conquer rule to break the problem into sub-problems, the problem in this case being, sorting a given array.
In merge sort, we break the given array midway, for example if the original array had 6
elements, then merge sort will break it down into two subarrays with 3
elements each.
But breaking the orignal array into 2 smaller subarrays is not helping us in sorting the array.
So we will break these subarrays into even smaller subarrays, until we have multiple subarrays with single element in them. Now, the idea here is that an array with a single element is already sorted, so once we break the original array into subarrays which has only a single element, we have successfully broken down our problem into base problems.
And then we have to merge all these sorted subarrays, step by step to form one single sorted array.
Let’s consider an array with values {14, 7, 3, 12, 9, 11, 6, 12}
Below, we have a pictorial representation of how merge sort will sort the given array.
In merge sort we follow the following steps:
- We take a variable
p
and store the starting index of our array in this. And we take another variabler
and store the last index of array in it. - Then we find the middle of the array using the formula
(p + r)/2
and mark the middle index asq
, and break the array into two subarrays, fromp
toq
and fromq + 1
tor
index. - Then we divide these 2 subarrays again, just like we divided our main array and this continues.
- Once we have divided the main array into subarrays with single elements, then we start merging the subarrays.