Lecture 8 MergeSort
Lecture 8 MergeSort
of Algorithms
Lecture 8
Instructor: Yusra Mansoor
Email: [email protected]
Designing
Many approaches
Insertion and Selection sort algorithm used the incremental approach
One of the powerful approach is the divide and conquer.
Divide-&-Conquer Approach
1. Divide the problem into sub problems,
2. Conquer the problems by solving them recursively
3. Combine the solutions to the sub problems into the final solution.
Merge Sort
Divide: divide the n element input into two subproblems
Conquer: sort the two sequences recursively,
Combine: merge the two sorted subsequences
Merge Sort
The merge
Walk through the two arrays simultaneously, in time linear in the total number
of elements
2 4 8 16 32 64 128 Array 1
1 2 3 5 8 13 21 34 Array 2
25
Analyzing Divide-and-Conquer algs.
When the algorithms contains recursive calls, the running time is described by a recurrence
equation or just recurrence.
For an input size n, let T(n) be the running time:
◦ we divide the problem into a parts of size b
◦ Let D(n) be the time to divide
◦ Let C(n) be the time to merge,
Analyzing Divide-and-Conquer algs.
For an input size n, let T(n) be the running time:
we divide the problem into a parts of size b
Let D(n) be the time to divide
Let C(n) be the time to merge,
Merge Sort:
Divide: Assuming input of even length
Conquer: for two subproblems,
Combine:
Merge Sort