Compared to Naïve method, in divide and conquer approach, the number of comparisons is less.
However,
using the asymptotic notation both of the approaches are represented by O(n).
4. Merge sort
The merge sort is a sorting algorithm that uses the divide and conquer strategy. In this method division is
dynamically carried out.
Sorting by merging is a recursive strategy, divide-and-conquer strategy. In the base case, we have a sequence
with exactly one element in it. Since such a sequence is already sorted, there is nothing to be done. To sort a
sequence of elements (n>1)
• Divide the sequence into two sequences of length n/2 and n/2
• Recursively sort each of the two subsequence’s; and then
• Merge the sorted subsequence’s to obtain the final list.
15 © www.tutorialtpoint.net Pepared by D.Venkata Reddy M.Tech(Ph.D), UGC NET, AP SET Qualififed
Divide: The divide step just computes the middle of the subarray. Which takes constant time, O(1)
Conquer: We recursively solve two subproblems, each size n/2, which contributes T(n2/)+T(n/2)
Combine: The merge procedure on an n-element subarray takes time O(n)
void merge_sort (int A[ ] , int start , int end )
if( start < end ) {
int mid = (start + end ) / 2 ; // defines the current array in 2 parts .
merge_sort (A, start , mid ) ; // sort the 1st part of array .
merge_sort (A,mid+1 , end ) ; // sort the 2nd part of array.
// merge the both parts by comparing elements of both the parts.
merge(A,start , mid , end );
Merge sort is a stable sorting algorithm. A sorting is said to be stable if it preserves the ordering of similar
elements after applying sorting method. And merge sort is a method preserves this kind of ordering. Hence
merge sort is a stable sorting algorithm.
Drawbacks:
• This algorithm requires extra storage to execute this method
• This method is slower than the quick sort method
• This method is complicated to code.
Time Complexity: O(n log(n)), Sorting arrays on different machines. Merge Sort is a recursive algorithm and
time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + θ(n)
16 © www.tutorialtpoint.net Pepared by D.Venkata Reddy M.Tech(Ph.D), UGC NET, AP SET Qualififed
17 © www.tutorialtpoint.net Pepared by D.Venkata Reddy M.Tech(Ph.D), UGC NET, AP SET Qualififed