Professional Documents
Culture Documents
Reading: Chapter 1
Cost Times
found = 0; C0 1
i = 0; C1 1
while (!found && i < N) { C2 0 <= L < N
if (key == X[i]) C3 1 <= L <= N
found = 1; C5 1
i++; C4 1 <= L <= N
}
● For some algorithms, the worst case happens fairly often. As in this
search example, the searched item is typically not in the array, so the
loop will iterate N times
● The “average case” is often roughly as bad as the “worst case”. In our
search algorithm, both the average case and the worst case are linear
functions of the input size “n”
❑ However, if the average case is the majority of all cases, then we
will focus on it.
● Like sorting, routing, etc
2019/9/9 CSCE 4113/5113: Algorithms 6
2.3.1
Maximum Value
❑ For example, the time taken to find the largest object in an array
of n random integers will take n operations
❑ Linear Search
int find_max( int *array, int n ) {
int max = array[0];
return max;
}
n
2019/9/9 CSCE 4113/5113: Algorithms 8
2.3.3
Quadratic Growth
❑ Consider the two functions
● f(n) = n2 and g(n) = n2 – 3n + 2
❑ Around n = 0, they look very different
f ( n)
● where lim =c 0c
n → g ( n)
f ( n)
● We will state that f < g if lim =0
n → g ( n)
f( n)
❑ If lim =c where 0 c , it follows that f(n) = O(g(n))
n →
g( n)
f( n)
● If lim
n →
= 0 , we will say f(n) = o(g(n))
g( n)
f( n)
❑ If lim =c where 0 c , it follows that f(n) = Q(g(n))
n →
g( n)
f( n )
f( n) = O(g( n)) lim
n→ g( n )
f( n )
f( n) = Θ(g( n)) 0 lim
n→ g( n )
f( n )
f( n) = Ω(g( n)) lim 0
n → g( n )
f( n )
f( n ) = ω(g( n )) lim =
n→ g( n )
❑ We say
❑ if
n2 100000 n2 – 4 n + 19 n2 + 1000000
323 n2 – 4 n ln(n) + 43 n + 10 42n2 + 32
n2 + 61 n ln2(n) + 7n + 14 ln3(n) + ln(n)
Q(1) constant
Q(ln(n)) logarithmic
Q(n) linear
Q(n ln(n)) “n log n”
Q(n2) quadratic
Q(n3) cubic
2n, en, 4n, ... exponential
250
f(n) = n
f(n) = log(n)
f(n) = n log(n)
f(n) = n^2
f(n) = n^3
f(n) = 2^n
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
5000
4000
f(n) = n
f(n) = log(n)
3000
f(n) = n log(n)
f(n) = n^2
2000 f(n) = n^3
f(n) = 2^n
1000
0
1 3 5 7 9 11 13 15 17 19
● Therefore an = o(bn)