0% found this document useful (0 votes)
43 views32 pages

Lecture 8 MergeSort

Uploaded by

paid games
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views32 pages

Lecture 8 MergeSort

Uploaded by

paid games
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Design and Analysis

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

Divide the input into:


MergeSort (Example) - 1
MergeSort (Example) - 2
MergeSort (Example) - 3
MergeSort (Example) - 4
MergeSort (Example) - 5
MergeSort (Example) - 6
MergeSort (Example) - 7
MergeSort (Example) - 8
MergeSort (Example) - 9
MergeSort (Example) - 10
MergeSort (Example) - 11
MergeSort (Example) - 12
MergeSort (Example) - 13
MergeSort (Example) - 14
MergeSort (Example) - 15
MergeSort (Example) - 16
MergeSort (Example) - 17
MergeSort (Example) - 18
Sec. 1.3

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

If list lengths are x and y, merge takes O(x+y) operations.

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

We shall show that

Merge sort vs. Insertion Sort


O(nlogn) sorts

You might also like