Javatpoint Logo
Javatpoint Logo

Merge Sort

It closely follows the divide & Conquers paradigm.

Conceptually, it works as follows:

  1. Divide: Divide the unsorted list into two sublists of about half the size.
  2. Conquer: Sort each of the two sublists recursively until we have list sizes of length 1, in which case the list items are returned.
  3. Combine: Join the two sorted Sub lists back into one sorted list.

The Main purpose is to sort the unsorted list in nondecreasing order.

ALGORITHM-MERGE SORT
1. If p<r
2. Then q ← ( p+ r)/2
3. MERGE-SORT (A, p, q)
4. MERGE-SORT ( A, q+1,r)
5. MERGE ( A, p, q ,r)

The following figure illustrates the dividing (splitting) procedure.

DAA Merge Sort
FUNCTIONS: MERGE (A, p, q, r)
1. n 1 = q-p+1
2. n 2= r-q
3. create arrays [1.....n 1 + 1] and R [ 1.....n 2 +1 ]
4. for i ← 1 to n 1
5. do [i] ← A [ p+ i-1]
6. for j ← 1 to n2
7. do R[j] ← A[ q + j]
8. L [n 1+ 1] ← ∞
9. R[n 2+ 1] ← ∞ 
10. I ← 1
11. J ← 1
12. For k ← p to r
13. Do if L [i] ≤ R[j]
14. then A[k] ← L[ i]
15. i ← i +1
16. else A[k] ← R[j]
17. j ← j+1
DAA Merge Sort

In this method, we split the given list into two halves. Then recursively analyzing merge sort and dividing. We get many sorted lists.

At last, we combine the sorted lists.

Analysis of Merge Sort:

Let T (n) be the total time taken in Merge Sort

  1. Sorting two halves will be taken at the most 2T DAA Merge Sorttime
  2. When we merge the sorted lists, we have a total n-1 comparison because the last element which will be left will just need to be copied down in the combined list and there will be no comparison.

So, the relational formula becomes

DAA Merge Sort

But we ignore '-1' because the element will take some time to be copied in merge lists.

So T (n) = 2TDAA Merge Sort + n.........equation 1

Note: Stopping Condition T (1) =0 because at last there will be only 1 element left which need to be copied and there will be no comparison.

DAA Merge Sort

Put 2 equation in 1 equation

DAA Merge Sort

Putting 4 equation in 3 equation

DAA Merge Sort

From Stopping Condition:

DAA Merge Sort

Apply log both sides:

log n=log2i
logn= i log2
DAA Merge Sort=i

log2n=i

From 6 equation

DAA Merge Sort
Next TopicTower of Hanoi




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA