Merge sort
1.Merge sort
This follow divide and conquer approach to create smaller sub-problems
A list is broken down into smaller and smaller parts recursively
Then merge the sorted lists together to get the fully sorted list
2.Divide and Conquer
A classic recursion based algorithm, divide till the problem is so small as to be trivial
Solve for the trivial case and then build up the complete solution as recursion unwinds
3.Code
The "split" method to split the list into 2 sub-lists
The "merge" method to merge 2 sorted lists into sorted list
The "mergeSort" method which does the final recursive sort
Split method (take Θ (n1 + n2) = Θ (n) time )
The two lists for the first and second halves have been setup and split simply copies the elements from the first list over
The first half holds everything up to the mid-point
The second half holds reminder of the elements
Merge method (take Θ (n) time )
Set up indices into the final merged list and the two halves which are to be merged together.
Compare the element at the current index of each of the lists and choose the smaller one to go into the final list
Copy over the remaining elements left in either one of the lists
MergeSort
4.Complexity
The complexity of Merge sort is O(NLogN)
The algorithm is not adaptive
It takes O(N) extra space when we use arrays (all the smaller lists we create in the divide phase)
It is a stable sort
Running time T(n) of merge sort:
Last updated