14

Merge Sort

Embed Size (px)

Citation preview

Page 1: Merge Sort
Page 2: Merge Sort

• Merge sort is a sorting technique which works based on DIVIDE AND CONQUER method

• This method uses recursion principle• Merge sort is the typical example of

Divide and Conquer

What is Merge sort?

Page 3: Merge Sort

This is a 3 phase technique

1. Divide step:- Divide input data S into disjoint subsets S1 ,S2,…

2. Recur:- Solve the Subsets S1,S2,…3. Combine:- Combine the subset solutions

Divide and Conquer

Page 4: Merge Sort

How it is Merge sort done?

Merge sort is done in 3 main steps:-1. Subdividing the main problem till the

problem becomes small enough.2. Solving the sub problem recursively3. Combining the solutions (merging) to get

the complete solution.

Page 5: Merge Sort

Technical stuff

The Algorithm for Merge_sort() can be written as:-

Merge_sort(input, start, limit){ if(start<limit) //if problem is large enough

{ div=(start + limit)/2;// here divided into 2 subpbms

Merge_sort(input, start, div);Merge_sort(input, div+1,limit);Merge(input, output, start, div, limit);

}}

Page 6: Merge Sort

Technical stuff

Similarly Algorithm for Merge() can be written as:-

Merge(input, output, start, div, limit){ j=0;

while(start<div||div<limit){if (input[start] < input[div]) // smaller one first

{output[j] = input[limit]; start++;}else {output[j] = input[div]; div++}j++;

} }

Page 7: Merge Sort

Time Complexity

There are three phases in this sorting techinique;The division phase, the conquer phase and finally combining the sub solutions.Division an combine takes O(n) while the Conquer step is O(log n)

That is:- T(n) = 2T (n/2) + O(n) yielding a net time of O(nlogn)

Page 8: Merge Sort

Time Complexity

Page 9: Merge Sort

Comparison

Page 10: Merge Sort

Non Divide and Conquer algorithms

Page 11: Merge Sort

Why this?

1. Speed2. High efficiency3. Better than Heap sort in the

case of large arrays

Page 12: Merge Sort

Short-comings

1. Efficiency not high for small arrays

2. Additional memory needed for the merge()

3. Usage of recursion means need of dynamic memory

Page 13: Merge Sort

References

1. www.wikipedia.org

2. Introduction to algorithms

By Thomas Cormen

Charles Leiserson

Ronald Rivest

3. http://linux.wku.edu/~lamonml/algor/sort/sort.html

4. http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/mergeSort.htm

Page 14: Merge Sort