Rinciples of Lgorithm Nalysis: Sedgewick: Chapter 2
Rinciples of Lgorithm Nalysis: Sedgewick: Chapter 2
Sedgewick: Chapter 2
1
COMP1927 Principles of Algorithm
Analysis
ANALYSIS OF SOFTWARE
ALGORITHM EFFICIENCY
The algorithm is by far the most important
determinant of the efficiency of a program
Small speed ups in terms of operating systems,
compilers, computers and implementation details
are irrelevant
input(n)
1000000
10000000
100000000
PREDICTING RUNTIME
If I know my algorithm is quadratic and I know that it
takes 1.2 seconds to run on a data set of size 1000
Approximately how long would you expect to wait
for a data set of size 2000?
What about 10000?
What about 100000?
What about 1000000?
What about 10000000?
Given an array a of N elements, with a[i] <= a[j] for any pair of
indices i,j, with i <= j < N,
int a[N];
// array with N items
int found = 0;
int i = 0;
while ((i < N) && (!found)){
found = (a[i] == e);
i++;
}
Given an array a of N elements, with a[i] <= a[j] for any pair of
indices i,j, with i <= j < N,
int a[N];
// array with N items
int found = 0;
int finished = 0;
int i = 0;
while ((i < N) && (!found) && (!finished)){
found = (a[i] == e);
exploit the fact that a is sorted
finished = (e < a[i]);
i++;
}
Best case: TN = 1
Worst case: TN = N
Average: TN = N/2
BINARY SEARCH
left and right index define an empty array, element not found
Eg l > r
if: a[(l+r)/2] is
a[l]..a[(l+r)/2-1]
a[(l+r)/2+1]..a[r]
Best case:
TN = 1
Worst case:
T1 = 1
TN = 1 + TN/2
TN = log2 N + 1
O(log n)
120
100
80
60
40
Binary search is a
logarithmic algorithm
20
0
10 20 30 40 50 60 70 80 90 10
BIG-O NOTATION
ANALYSING ALGORITHMS
log n
nlogn
n^2
2^n
10
40
100
1024
100
700
10000
1.3E+30
1000
10
10000
1000000
REALLY
BIG
10000
14
140000
100000000
100000
17
1700000
10000000000
1000000
20
20000000
1000000000000