0% found this document useful (0 votes)
13 views45 pages

1 AlgorithmAnalysis

The document provides an overview of algorithms, defining them as a set of instructions for solving problems and emphasizing the importance of correctness and efficiency. It discusses performance measures such as running time and memory requirements, along with methods for analyzing algorithms independently of specific implementations. The document also covers growth rates of algorithms using Big O notation to compare their efficiency based on problem size.

Uploaded by

pelin sağırer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views45 pages

1 AlgorithmAnalysis

The document provides an overview of algorithms, defining them as a set of instructions for solving problems and emphasizing the importance of correctness and efficiency. It discusses performance measures such as running time and memory requirements, along with methods for analyzing algorithms independently of specific implementations. The document also covers growth rates of algorithms using Big O notation to compare their efficiency based on problem size.

Uploaded by

pelin sağırer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Algorithm Analysis

CEN 203 Data Structures 1


Algorithm
• An algorithm is a set of instructions to be
followed to solve a problem.

– There can be more than one solution (more than one


algorithm) to solve a given problem.
– An algorithm can be implemented using different
programming languages on different platforms.

CEN 203 Data Structures 2


Algorithms (cont.)
• An algorithm must be correct. It should
correctly solve the problem.
e.g. For sorting, this means even if
i. the input is already sorted, or
ii. it contains repeated elements.

• Once we have a correct algorithm for a problem,


we have to determine the efficiency (running
time performance and memory requirement) of
that algorithm.
CEN 203 Data Structures 3
Performance Measures of Algorithms
There are two performance measures for
algorithms:

1. Running Time
• Every instruction takes time.
• How fast does the algorithm perform?
• What affects its runtime?
• If an algorithm requires years to run on an average
computer, then it is not useful.

CEN 203 Data Structures 4


Performance Measures of Algorithms
(cont.)
2. Space (Memory Requirement)

• Data structures take space


• What kind of data structures can be used?
• How does choice of data structure affect the runtime?
• If an algorithm requires several gigabytes of main
memory to run, then it is not useful.

CEN 203 Data Structures 5


Content that we will cover

• We will focus on running time:


– How to estimate the time required for an
algorithm
– How to reduce the time required for an
algorithm.
• We will also explain how to estimate
memory requirement of an algorithm.

CEN 203 Data Structures 6


Analysis of Algorithms
• Analysis of Algorithms is the area of
computer science that provides tools to
analyze the efficiency of different methods
of solutions.
• How do we compare the time efficiency of
two algorithms that solve the same
problem?

CEN 203 Data Structures 7


Analysis of Algorithms
Naïve Approach: implement these
algorithms in a programming language
(C), and run them to compare their
time requirements.

CEN 203 Data Structures 8


Analysis of Algorithms
Comparing the programs (instead of
algorithms) has difficulties.
– How are the algorithms coded?
• Comparing running times means comparing the
implementations.
• We should not compare implementations, because they are
sensitive to programming style.
– What computer should we use?
• We should compare the efficiency of the algorithms
independently of a particular computer (hardware).
– What data should the program use?
• Any analysis must be independent of specific data.

CEN 203 Data Structures 9


Analysis of Algorithms
• When we analyze algorithms, we should employ
mathematical techniques that analyze algorithms
independently of specific implementations,
computers, or data.

• To analyze running time of algorithms:


– First, we start to count the number of significant
operations in a particular solution to assess its
efficiency.
– Then, we will express the efficiency of algorithms
using growth functions.

CEN 203 Data Structures 10


Running Time
• Running time of an algorithm is a function of
the input size such that it gives the time
requirement of the algorithm to solve the problem
for a given input.
• To compute running time of an algorithm, the
number of computations that were made by the
algorithm such as:
• Number of assignment statements,
• Number of arithmetical computations (+, -, *, /),
• Number of iterations,
• Number of disk accesses, etc.
are computed.

CEN 203 Data Structures 11


Running Time
• As running time of an algorithm, time in
terms of seconds or minutes is not
measured, because
e.g.,
Algorithm A runs in 30 seconds in
computer C1, the same algorithm A runs in
0.001 seconds in computer C2.
Instead, we do running time analysis.
CEN 203 Data Structures 12
The Running Time of Algorithms
• Each operation in an algorithm (or a program) has a cost.
 Each operation takes a certain of time.

count = count + 1;  take a certain amount of time, but it is constant

A sequence of operations:

count = count + 1; Cost: c1


sum = sum + count; Cost: c2

 Total Cost = c1 + c2

CEN 203 Data Structures 13


The Running Time of Algorithms (cont.)
Example: Simple If-Statement
Cost Times
if (n < 0) c1 1
result = -1*n; c2 1
else
result = n; c3 1

Total Cost <= c1 + max(c2,c3)

CEN 203 Data Structures 14


The Execution Time of Algorithms (cont.)
Example: Simple Loop
Cost Times
i = 1; c1 1
sum = 0; c2 1
while (i <= n) { c3 n+1
i = i + 1; c4 n
sum = sum + i; c5 n
}

Total Cost = c1 + c2 + (n+1)*c3 + n*c4 + n*c5


 The time required for this algorithm is proportional to n

CEN 203 Data Structures 15


The Execution Time of Algorithms (cont.)
Example: Nested Loop
Cost Times
i=1; c1 1
sum = 0; c2 1
while (i <= n) { c3 n+1
j=1; c4 n
while (j <= n) { c5 n*(n+1)
sum = sum + i; c6 n*n
j = j + 1; c7 n*n
}
i = i +1; c8 n
}
Total Cost = c1 + c2 + (n+1)*c3 + n*c4 + n*(n+1)*c5+n*n*c6+n*n*c7+n*c8
 The time required for this algorithm is proportional to n2

CEN 203 Data Structures 16


General Rules for Estimation
• Loops: The running time of a loop is at most the running time
of the statements inside of that loop times the number of
iterations.
• Nested Loops: Running time of a nested loop containing a
statement in the inner most loop is the running time of statement
multiplied by the product of the sized of all loops.
• Consecutive Statements: Just add the running times of those
consecutive statements.
• If/Else: Never more than the running time of the test plus the
larger of running times of S1 and S2.

CEN 203 Data Structures 17


Algorithm Growth Rates
• We measure an algorithm’s time requirement as a function of the
problem size.
– Problem size depends on the application: e.g. number of elements in a list for a
sorting algorithm, the number disks for towers of hanoi.
• So, for instance, we say that (if the problem size is n)
– Algorithm A requires 5*n2 time units to solve a problem of size n.
– Algorithm B requires 7*n time units to solve a problem of size n.
• The most important thing to learn is how quickly the algorithm’s
time requirement grows as a function of the problem size.
– Algorithm A requires time proportional to n2.
– Algorithm B requires time proportional to n.
• An algorithm’s proportional time requirement is known as
growth rate.
• We can compare the efficiency of two algorithms by comparing
their growth rates.
CEN 203 Data Structures 18
Algorithm Growth Rates (cont.)

Time requirements as a function


of the problem size n

CEN 203 Data Structures 19


Common Growth Rates
Function Growth Rate Name
c Constant
log N Logarithmic
log2N Log-squared
N Linear
N log N Log with linear multiplier
N2 Quadratic
N3 Cubic
2N Exponential
N! Factorial
CEN 203 Data Structures 20
Figure 6.1
Running times for small inputs

CEN 203 Data Structures 21


Figure 6.2
Running times for moderate inputs

CEN 203 Data Structures 22


Order-of-Magnitude Analysis and Big O
Notation
• If Algorithm A requires time proportional to f(n), Algorithm A is
said to be order f(n), and it is denoted as O(f(n)).
• The function f(n) is called the algorithm’s growth-rate
function.
• Since the capital O is used in the notation, this notation is called
the Big O notation.
• If Algorithm A requires time proportional to n2, it is O(n2).
• If Algorithm A requires time proportional to n, it is O(n).

CEN 203 Data Structures 23


Definition of the Order of an Algorithm
Definition:
Algorithm A is order f(n) – denoted as O(f(n)) –
if constants c and n0 exist such that A requires
no more than c*f(n) time units to solve a problem
of size n  n0.

• The requirement of n  n0 in the definition of O(f(n)) formalizes


the notion of sufficiently large problems.
– In general, many values of c and n can satisfy this definition.

CEN 203 Data Structures 24


Order of an Algorithm
• If an algorithm requires n2–3 n+10 seconds to solve a problem
size n. If constants k and n0 exist such that
c n2 > n2–3 n+10 for all n  n0 .
the algorithm is order n2 (In fact, c is 3 and n0 is 2)
3 n2 > n2–3 n+10 for all n  2 .
Thus, the algorithm requires no more than c*n2 time units for n 
n0 ,
So it is O(n2)

CEN 203 Data Structures 25


Order of an Algorithm (cont.)

CEN 203 Data Structures 26


A Comparison of Growth-Rate Functions

CEN 203 Data Structures 27


A Comparison of Growth-Rate Functions (cont.)

CEN 203 Data Structures 28


Growth-Rate Functions
O(1) Time requirement is constant, and it is independent of the problem’s size.
O(log2n) Time requirement for a logarithmic algorithm increases slowly as the problem
size increases.
O(n) Time requirement for a linear algorithm increases directly with the size
of the problem.
O(n*log2n) Time requirement for a n*log2n algorithm increases more rapidly than
a linear algorithm.
O(n2) Time requirement for a quadratic algorithm increases rapidly with the
size of the problem.
O(n3) Time requirement for a cubic algorithm increases more rapidly with the
size of the problem than the time requirement for a quadratic algorithm.
O(2n) As the size of the problem increases, the time requirement for an
exponential algorithm increases too rapidly to be practical.

CEN 203 Data Structures 29


Growth-Rate Functions
• If an algorithm takes 1 second to run with the problem size 8,
what is the time requirement (approximately) for that algorithm
with the problem size 16?
• If its order is:
O(1)  T(n) = 1 second
O(log2n)  T(n) = (1*log216) / log28 = 4/3 seconds
O(n)  T(n) = (1*16) / 8 = 2 seconds
O(n*log2n)  T(n) = (1*16*log216) / 8*log28 = 8/3 seconds
O(n2)  T(n) = (1*162) / 82 = 4 seconds
O(n3)  T(n) = (1*163) / 83 = 8 seconds
O(2n)  T(n) = (1*216) / 28 = 28 seconds = 256 seconds

CEN 203 Data Structures 30


Properties of Growth-Rate Functions
1. We can ignore low-order terms in an algorithm’s growth-rate
function.
– If an algorithm is O(n3+4n2+3n), it is also O(n3).
– We only use the higher-order term as algorithm’s growth-rate function.

2. We can ignore a multiplicative constant in the higher-order term


of an algorithm’s growth-rate function.
– If an algorithm is O(5n3), it is also O(n3).

3. O(f(n)) + O(g(n)) = O(f(n)+g(n))


– We can combine growth-rate functions.
– If an algorithm is O(n3) + O(4n), it is also O(n3 +4n2)  So, it is O(n3).
– Similar rules hold for multiplication.

CEN 203 Data Structures 31


Some Mathematical Facts
• Some mathematical equalities are:
n
n * (n  1) n 2

i 1
i  1  2  ...  n 
2

2

n
n * ( n  1) * ( 2 n  1) n 3


i 1
i 2
 1  4  ...  n 2

6

3

n 1

 2
i 0
i
 0  1  2  ...  2 n 1
 2 n
1

CEN 203 Data Structures 32


Growth-Rate Functions – Example1
# of operations Times
i = 1; 1 1
sum = 0; 1 1
while (i <= n) { 1 n+1
i = i + 1; 2 n
sum = sum + i; 2 n
}

T(n) = 1 + 1 + (n+1)*1 + n*2 + n*2


= (1+2+2)*n + (1+1+1)
= 5*n + 3
 So, the growth-rate function for this algorithm is O(n)

CEN 203 Data Structures 33


Growth-Rate Functions – Example2
# of operations Times
i=1; 1 1
sum = 0; 1 1
while (i <= n) { 1 n+1
j=1; 1 n
while (j <= n) { 1 n*(n+1)
sum = sum + i; 2 n*n
j = j + 1; 2 n*n
}
i = i +1; 2 n
}
T(n) = 1 + 1 + (n+1)*1 + n*1 + n*(n+1)*1 + n*n*1 + n*n*2 + n*2
= (1+1+2)*n2 + (1+1+1+2)*n + (1+1+1)
= 4*n2 + 5*n + 3
 So, the growth-rate function for this algorithm is O(n2)
CEN 203 Data Structures 34
Growth-Rate Functions – Example3
# of operations Times
for (i=1; i<=n; i++) 1,1,1 1,n+1,n
n n

for (j=1; j<=i; j++) 1,1,1 n,  (i  1) , i


i 1 i 1
n n i n i

for (k=1; k<=j; k++) 1,1,1  i,  ( j  1)


i 1 i 1 j 1
,  j
i 1 j 1
n i

x=x+1; 2  j
i 1 j 1
n n n
T(n) = 1+ 1*(n+1) + 1*n + 1*n + 1*(  (i  1) ) + 1* (  i
i 1 i 1
) + 1*( i ) +
i 1
n i n i n i
1*(  ( j  1)) + 1* (  j ) +2*(  j
i 1 j 1
)
i 1 j 1 i 1 j 1

= a*n3 + b*n2 + c*n + d


 So, the growth-rate function for this algorithm is O(n3)
CEN 203 Data Structures 35
Growth-Rate Functions – Example 4
Running time analysis of a function that computes the average of the
elements of an array.

float computeAvg(float A[ ], int n){


float avg, total=0;
int k;
for (k = 0; k < n; k++)
total = total + A[k];
avg = total / n;
return(avg);
}

CEN 203 Data Structures 36


Growth-Rate Functions – Example 5
Running time analysis of findMin( ) function which finds and
returns the minimum element of an array having n element.

float findMin(float A[ ], int n){


float min;
int k;
min = A[0];
for (k = 1; k < n; k++){
if (A[k] < min){
min = A[k];
}
}
return min;
}
CEN 203 Data Structures 37
Growth-Rate Functions – Example 6
Running time analysis of MatrixSum( ) function which adds 2 n*m
matrices A and B into matrix C.

void matrixSum(int A[ ][100], int B[ ][100], int C[ ][100], int n, int


m){
int i, j;
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
C[i][j] = A[i][j] + B[i][j];
}
}
}
CEN 203 Data Structures 38
Growth-Rate Functions – Recursive Algorithms
void hanoi(int n, char source, char dest, char spare) { #of op.
if (n > 0) { 1
hanoi(n-1, source, spare, dest); c1
printf("Move top disk from pole %c 1
to pole %c\n ", source, dest);
hanoi(n-1, spare, dest, source); c2
} }

• The time-complexity function T(n) of a recursive algorithm is


defined in terms of itself, and this is known as recurrence equation
for T(n).
• To find the growth-rate function for a recursive algorithm, we have
to solve its recurrence relation.

CEN 203 Data Structures 39


Growth-Rate Functions – Hanoi Towers
• What is the cost of hanoi(n,’A’,’B’,’C’)?

when n=0
T(0) = 1

when n>0
T(n) = 1 + c1 + T(n-1) + 1 + c2 + T(n-1)
= 2*T(n-1) + (1+c1+1+c2)
= 2*T(n-1) + c  recurrence equation for the growth-rate
function of hanoi-towers algorithm

• Now, we have to solve this recurrence equation to find the growth-rate


function of hanoi-towers algorithm

CEN 203 Data Structures 40


Growth-Rate Functions – Hanoi Towers (cont.)
• There are many methods to solve recurrence equations, but we will use a simple
method known as repeated substitutions.

T(n) = 2*T(n-1) + c
= 2 * (2*T(n-2)+c) + c
= 2 * (2* (2*T(n-3)+c) + c) + c
= 23 * T(n-3) + (22+21+20)*c (assuming n>2)
when substitution repeated i-1th times
= 2i * T(n-i) + (2i-1+ ... +21+20)*c
when i=n
= 2n * T(0) + (2n-1+ ... +21+20)*c
n 1
= 2 * c1 + (  2i )*c
n
i 0

= 2n * c1 + ( 2n-1 )*c = 2n*(c1+c) – c  So, the growth rate function is O(2n)


CEN 203 Data Structures 41
What to Analyze
• An algorithm can require different times to solve different
problems of the same size.
– Eg. Searching an item in a list of n elements using sequential search.  Cost:
1,2,...,n
• Worst-Case Analysis –The maximum amount of time that an
algorithm require to solve a problem of size n.
– This gives an upper bound for the time complexity of an algorithm.
– Normally, we try to find worst-case behavior of an algorithm.
• Best-Case Analysis –The minimum amount of time that an
algorithm require to solve a problem of size n.
– The best case behavior of an algorithm is NOT so useful.
• Average-Case Analysis –The average amount of time that an
algorithm require to solve a problem of size n.
– Sometimes, it is difficult to find the average-case behavior of an algorithm.
– We have to look at all possible data organizations of a given size n, and their
distribution probabilities of these organizations.
– Worst-case analysis is more common than average-case analysis.
CEN 203 Data Structures 42
Memory Requirement of a Computer Program
• It is the amount of memory that is needed to run the program.
• It involves three components:
1. Memory requirement of the source code: equal to the size of
the .exe file of the source code. It can be computed after the
source code is compiled.
2. Memory requirement of the data: is the amount of meomory
to store the variables, data structures, and the arrays of the
source code. We can compute this value.
3. Memory requirement of the program stack: If the source
code does not include a recursive function, we can ignore this
memory requirement.
 So, do not use recursion!

CEN 203 Data Structures 43


Example
• Compute the memory requirement of data used in the below
source code:
main(){ # of bytes needed
int A[20] = {7, 62, 3, 21, …}; 20 * 4
int k, sum; 4+4
float avg; 4
for (k = 0; k < 20; k++)
sum += A[k];
avg = sum / 20.0;
printf("Average of the 20 elements=%f\n", avg);
}
 Total bytes for the data = 80 + 8 + 4 = 92 bytes.
CEN 203 Data Structures 44
What is Important?

• If the problem size is always small, we can probably ignore the


algorithm’s efficiency.
– In this case, we should choose the simplest algorithm.
• We have to weigh the trade-offs between an algorithm’s time
requirement and its memory requirements.
• We have to compare algorithms for both style and efficiency.
– The analysis should focus on gross differences in efficiency and not reward coding
tricks that save small amount of time.
– That is, there is no need for coding tricks if the gain is not too much.
– Easily understandable program is also important.
• Order-of-magnitude analysis focuses on large problems.

CEN 203 Data Structures 45

You might also like