1 algorithms csci 235, fall 2015 lecture 7 recurrences ii

9
1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

Upload: berenice-norman

Post on 18-Jan-2018

212 views

Category:

Documents


0 download

DESCRIPTION

3 Pseudo code for Merge Sort {merge-sort(A, 1, length[A]) is initial call} {merge-sort(A, p, r)} if p = r then empty or single item} q  (p + r)/2 { p is the floor of p } merge-sort(A, p, q) merge-sort(A, q+1, r) merge (A, p, q, r) Size of each subproblem = ? Number of subproblems = ? Running time of merge = ? Equation for Merge Sort: ?

TRANSCRIPT

Page 1: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

1

Algorithms

CSCI 235, Fall 2015Lecture 7

Recurrences II

Page 2: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

2

Recall Merge Sort

U N S O R T E D

U N S O R T E D

U N S O R T E D

U N S O R T E D

U N S O R T E D

UN SO R T ED

UN SO R TED

UN SO R TED

Divide in 1/2repeatedly

merge insorted order

Page 3: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

3

Pseudo code for Merge Sort

{merge-sort(A, 1, length[A]) is initial call}{merge-sort(A, p, r)}if p < r then {if p >= r then empty or single item}

q (p + r)/2 { p is the floor of p }merge-sort(A, p, q)merge-sort(A, q+1, r)merge (A, p, q, r)

Size of each subproblem = ?Number of subproblems = ?Running time of merge = ?Equation for Merge Sort: ?

Page 4: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

4

Example 1Working toward merge-sort

A simpler equation: T(n) = T(n/2) + 1

We will draw the recursion tree for this in class.

Page 5: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

5

Solution for Example 1

Total cost = (# levels)*(cost of each level)= ?

T(n) = ?

Number of levels = ?

Cost of each level = ?

Page 6: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

6

Example 2(working toward merge-sort)

Another equation: T(n) = 2T(n/2) + 1

Page 7: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

7

Solution for example 2

T(n) = 1 + 2 + 4 + 8 + ... + 2lg(n)

T(n) = ?

Page 8: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

8

Example 3merge-sort

merge-sort equation: T(n) = 2T(n/2) + n

Page 9: 1 Algorithms CSCI 235, Fall 2015 Lecture 7 Recurrences II

9

Solving Recursion tree for Merge-Sort

Total cost = (# levels)*(cost of each level)= ?

T(n) =

Number of levels = ?

Cost of each level = ?