Docsity

Recursive Functions and Algorithm Analysis - Prof. David J. Galles, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Recursive Functions and Algorithm Analysis - Prof. David J. Galles and more Study notes Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms

CS245-2009S-

Recursive Function Analysis

David Galles

Department of Computer Science

University of San Francisco

03-0:

Algorithm Analysis

for (i=1; i<=n*n; i++)

for (j=0; j<i; j++)

sum++;

03-2:

Algorithm Analysis

for (i=1; i<=n*n; i++)

for (j=0; j<i; j++)

sum++;

Exact # of times

sum++

is executed:

(^2) n ∑ i=

i^

n

n

2

n

4

n

2 2

n

03-3:

Recursive Functions

long power(long x, long n) {

if (n == 0)

return 1; else

return x * power(x, n-1);

03-5:

Recurrence Relations

long power(long x, long n) {

if (n == 0)

return 1; else

return x * power(x, n-1);

}^ T

c

1

for some constant

c

1

T

n

c

2

T

n

for some constant

c

2

03-6:

Solving Recurrence Relations

T

c

1

T

n

T

n

c

2

If we knew

T

n

, we could solve

T

n

T

n

)^

=

T

n

c

2

03-8:

Solving Recurrence Relations

T

c

1

T

n

T

n

c

2

If we knew

T

n

, we could solve

T

n

T

n

)^

=

T

n

c

2

T

n

T

n

c

2

=

T

n

c

2

c

2

=

T

n

c^2

T

n

T

n

c

2

=

T

n

c

2

c^2

=

T

n

c^2

03-9:

Solving Recurrence Relations

T

c

1

T

n

T

n

c

2

If we knew

T

n

, we could solve

T

n

T

n

)^

=

T

n

c

2

T

n

T

n

c

2

=

T

n

c

2

c

2

=

T

n

c^2

T

n

T

n

c

2

=

T

n

c

2

c^2

=

T

n

c^2

T

n

T

n

c

2

=

T

n

c^2

03-11:

Solving Recurrence Relations

T

c

1

T

n

T

n

k

k

c

2

for all

k

If we set

k

n

, we have:

T

n

)^

=

T

n

n

nc

2

=

T

nc

2

=

c

1

nc

2

n

03-12:

Building a Better

Power

long power(long x, long n) {

if (n==0) return 1;if (n==1) return x;if ((n % 2) == 0)

return power(x*x, n/2); else

return power(x*x, n/2) * x;

03-14:

Solving Recurrence Relations

T

n

)^

=

T

n/

c

3

03-15:

Solving Recurrence Relations

T

n

)^

=

T

n/

c

3

T

n/

T

n/

c

3

=

T

n/

c

3

c

3

=

T

n/

c^3

03-17:

Solving Recurrence Relations

T

n

)^

=

T

n/

c

3

T

n/

T

n/

c

3

=

T

n/

c

3

c

3

=

T

n/

c^3

T

n/

T

n/

c

3

=

T

n/

c

3

c^3

=

T

n/

c^3

T

n/

T

n/

c

3

=

T

n/

c

3

c^3

=

T

n/

c^3

03-18:

Solving Recurrence Relations

T

n

)^

=

T

n/

c

3

T

n/

T

n/

c

3

=

T

n/

c

3

c

3

=

T

n/

c^3

T

n/

T

n/

c

3

=

T

n/

c

3

c^3

=

T

n/

c^3

T

n/

T

n/

c

3

=

T

n/

c

3

c^3

=

T

n/

c^3

T

n/

T

n/

c

3

=

T

n/

c

3

c^3

=

T

n/

c^3