04 Fundamentals
04 Fundamentals
Other References
Data Structures 2
Mathematical Background
Data Structures 3
Powers of 2
0 k 2n-1
Data Structures 4
Unsigned binary numbers
Data Structures 5
Binary, Hex, and Decimal
28=256
27=128
26=64
25=32
24=16
21=2
22=4
23=8
20=1
Hex16 Decimal10
1 1 0x3 3
1 0 0 1 0x9 9
1 0 1 0 0xA 10
1 1 1 1 0xF 15
1 0 0 0 0 0x10 16
1 1 1 1 1 0x1F 31
1 1 1 1 1 1 1 0x7F 127
1 1 1 1 1 1 1 1 0xFF 255
Data Structures 6
Logs and exponents
Notice that log2x tells you how many bits are needed to
hold x values
8 bits holds 256 numbers: 0 to 28-1 = 0 to 255
log2256 = 8
Data Structures 7
x = 0:.1:4
y = 2.^x
plot(x,y,'r')
hold on
plot(y,x,'g')
plot(y,y,'b')
2x and log2x
Data Structures
x = 0:10
y = 2.^x
plot(x,y,'r')
hold on
plot(y,x,'g')
plot(y,y,'b')
2x and log2x
Data Structures
Example: log2x and tree depth
2 6
1 3 5 7
Data Structures 10
Properties of logs (of the mathematical
kind)
Data Structures 11
Other log properties
log A/B = log A – log B
log (AB) = B log A
log log X < log X < X for all X > 0
log log X = Y means
log X grows slower than X
2Y
2 X
called a “sub-linear” function
Data Structures 12
A log is a log is a log
Data Structures 13
Arithmetic Series
N
S (N ) 1 2 N i
i 1
The sum is
S(1) = 1
S(2) = 1+2 = 3
S(3) = 1+2+3 = 6
N
N ( N 1)
i 1
i
2
Why is this formula useful?
Data Structures 14
Quicky Algorithm Analysis
Data Structures 15
What is actually being executed?
The program segment being analyzed:
for (i = 1; i <= N; i++)
for (j = 1; j <= i; j++)
printf(“Hello\n”);
Inner loop executes “printf” i times in the ith iteration
j goes from 1 to i
There are N iterations in the outer loop
i goes from 1 to N
Data Structures 16
Lots of hellos
Data Structures 17
Recursion
Data Structures 18
Recursive Procedure for Fibonacci
Numbers
int fib(int i) {
if (i < 0) return 0;
if (i == 0 || i == 1)
return 1;
else
return fib(i-1)+fib(i-2);
}
Easy to write: looks like the definition of Fn
But, can you spot the big problem?
Data Structures 19
Recursive Calls of Fibonacci Procedure
Data Structures 20
Iterative Procedure for Fibonacci Num-
bers
int fib_iter(int i) {
int fib0 = 1, fib1 = 1, fibj = 1;
if (i < 0) return 0;
for (int j = 2; j <= i; j++) {
fibj = fib0 + fib1;
fib0 = fib1;
fib1 = fibj;
}
return fibj;
}
More variables and more bookkeeping but avoids
repetitive calculations and saves time.
Data Structures 21
Recursion Summary
Data Structures 22
Motivation for Algorithm Analysis
Run Time
lem
The running times
TA(N) and TB(N) of A
and B as a function of TB
input size N are given
Input Size N
Which is better?
Data Structures 23
More Motivation
For large N, the running time of A and B is:
Now which
algorithm would
Run Time
TA(N) = 50N
you choose?
TB(N) = N2
Input Size N
Data Structures 24
Asymptotic Behavior
Data Structures 25