0% found this document useful (0 votes)
9 views193 pages

Notes DAA

The document provides a comprehensive overview of algorithms, including their definition, properties, design techniques, and verification methods. It discusses various algorithmic strategies such as brute force, divide-and-conquer, and dynamic programming, along with the importance of pseudo code and performance analysis. Additionally, it covers time and space complexity, implementation, and testing of algorithms with examples to illustrate key concepts.

Uploaded by

N. Balaji
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)
9 views193 pages

Notes DAA

The document provides a comprehensive overview of algorithms, including their definition, properties, design techniques, and verification methods. It discusses various algorithmic strategies such as brute force, divide-and-conquer, and dynamic programming, along with the importance of pseudo code and performance analysis. Additionally, it covers time and space complexity, implementation, and testing of algorithms with examples to illustrate key concepts.

Uploaded by

N. Balaji
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
You are on page 1/ 193

UNIT-1

Algorithm: The word algorithm comes from the name of a Persian author „Abu Jafar
Mohammed ibn Musa al Khowarizmi‟, who wrote a text book on mathematics. According to
him an algorithm is a set of rules used to perform some calculations either by hand (or) more
usually on a machine.
(or)

An algorithm is a finite set of instructions to accomplish a particular task.

Properties (or) Characteristics of Algorithm:


 Input: Zero or more quantities are externally supplied.
 Output: Atleast one quantity is produced.
 Definiteness: Each instruction is clear and unambiguous
 Finiteness: If we trace out the instructions of an algorithm, then for all cases the
algorithm terminates after a finite number of steps.
 Effectiveness: Every instruction must be very basic so that it can be carried out in
principle by a person using only pencil and paper.

Design of Algorithm: The study of algorithm includes many important and active areas
of researches. They are:

 Understanding the problem: This is the very first step in designing of an algorithm.
In this step first of all need to understand the problem statement completely by
reading the problem description carefully. After that, find out what are the necessary
inputs for solving that problem. The input to the algorithm is called instance of the
problem. It is very important to decide the range of inputs so that the boundary
values of algorithm get fixed. The algorithm should work correctly for all valid
inputs.

 Decision Making: After finding the required input set for the given problem we have
to analyze the input and need to decide certain issues such as
Capabilities of computational devices: It is necessary to know the
computational capabilities of devices on which the algorithm will be running
ie sequential or parallel algorithm. Complex problems require huge amount of
memory and more execution time. For solving such problems it is essential to
have proper choice of a computational device which is space and time
efficient.
Choice for either exact or approximate problem solving method: The next
important decision is to decide whether the problem is to be solved exactly or
approximately. If the problem needs to be solved correctly then we need exact
algorithm. Otherwise, if the problem is so complex then we need
approximation algorithm.(Example: Salesperson Problem)
Data Structures: Data Structure and algorithm work together and these are
interdependent. Hence choice of proper data structure is required before
designing the actual algorithm.
Algorithmic Strategies: It is a general approach by which many problems can
be solved algorithmically. Algorithmic strategies are also called as algorithmic
techniques or algorithmic paradigm.
Algorithm Design Techniques:
 Brute Force: This is straight forward technique with naïve approach.
 Divide-and-Conquer: The problem is divided into smaller instances.
 Dynamic Programming: The results of smaller, reoccurring instances
are obtained to solve the problem.
 Greedy Technique: To solve the problem locally optimal decisions are
made.
 Back tracking: This method is based on the trial and error.
 Specification of Algorithm: There are various ways to specify an algorithm
 Using natural language: It is very simple to specify an algorithm using natural
language
For Example: Write an algorithm to perform addition of two numbers.
Step1: Read the first number say a.
Step2: Read the second number say b.
Step3: Add the two numbers and store the result in a variable c.
Step 4: Display the result.
 Pseudo code: It is a combination of natural language and programming
language
Algorithm sum(a,b):
// Addition of two numbers
//Input: Two numbers a and b
//Output: sum of numbers
{
c=a+b;
Write(c)
}
 Flowchart: Flowchart is a graphical representation of an algorithm
Start/ Stop state:

Transition:

Processing or assignment statement:

Conditional Statement:
 Algorithm Verification: Algorithm verification means checking correctness of an
algorithm that is to check whether the algorithm gives correct output in finite amount
of time for a valid set of input.

 Analysis of algorithm: The following factors should consider while analyzing an


algorithm
o Time Complexity: The amount of time taken by an algorithm to run.
o Space Complexity: The amount of space taken by an algorithm to store
variable.
o Range of Input: The design of an algorithm should be such that it should
handle the range of input.
o Simplicity: Simplicity of an algorithm means generating sequence of
instructions which are easy to understand.
o Generality: Generality shows that sometimes it becomes easier to design an
algorithm in more general way rather than designing it for particular set of
input.(Example: GCD)
 Implementation of Algorithm: The implementation of an algorithm is done by
suitable programming language.
 Testing a Program: Testing a program is an activity carried out to expose as many
errors as possible and to correct them.
There are two phases for testing a program:
 Debugging
 Profiling
Debugging is a technique in which a sample set of data is tested to see
whether faulty results occur or not. If any faulty result occurs then those
results are corrected.
But in Debugging technique only presence of error is pointed out. Any hidden
error cannot be identified.
So, we cannot verify correctness of output on sample data. Hence, Profiling
Concept is introduced.
Profiling or Performance Measurement is the process of executing a correct
program on a sample set of data. Then the time and space required by the
program to execute is measured.

Pseudo Code for Expressing Algorithms: In computational theory, we distinguish


between an algorithm and a program conventions used in writing a pseudo code. Pseudo code
is a combination of natural language and programming language.

Pseudo code is divided into two parts

Algorithm Heading which contains the keyword algorithm, name of


algorithm, Parameters, Problem Description, Input and Output.
Example: Algorithm name(p1,p2..pn)
// problem description
// Input
//Output
 Comments begin with // and continuous until the end of line.
Algorithm Body which consists of logical body of the algorithm by
making use of various programming constructs and assignment
statement
 Block of statements that are enclosed within „{ }‟
 Each statement is ended with delimiter „ ; ‟
 An identifier begins with a letter not by digit and can contain
combination of letters and numbers
 Data types are not declared but we assume simple data types
like int, float, char etc.
 The compound data types are represented with node. If an
instance of „P‟ is created to a node then the values of node can
be accessed by using the operator ( . ) or
Node = record
{
Datatype1 Variable;
Datatype2 Variable;

 Assignment of value to a variable is done using assignment


statement
Variable := Expression;
Variable Expression;
 Logical operators such as AND, OR, NOT and Relational
operators such as <,>,<=,>=,==,= are used to get a Boolean
values true or false.
 The array indices are stored within square brackets “[ ]”. The
multidimensional arrays can also be used in algorithm.

Example: A[i]- Single Dimensional Array, A[i,j]-2D Array

 Loop statements like for, while, repeat until are represented as


follows
for i:=1 to n
{
Statement 1;
Statement 2;
}

while (condition) do repeat


{ {
Statement 1; Statement 1;
Statement 2; Statement 2;
} } until (condition)

 Conditional Statements such as if-then or if-then-else are


represented as follows:
if(condition) then if(condition) then
{ {
Statement 1; Statement 1;
Statement 2; Statement 2;
} }

else

{
Statement 1;
Statement 2;
}

 Input and output are represented by using read and write


read (val);
write (stmt);

Example 1: Algorithm Max(A,n)


// A is an array of size n
{
Result:=A[1];
for i:=2 to n do
if A[i]>Result then Result:=A[i];
return Result;
}
Example 2: Algorithm even or odd (n)
// Finding whether given number is even or odd
{
if(n%2==0)
write(even);
else
write(odd);
}

Example 3: Algorithm Selection Sort(a,n)


// Sort the array in Ascending order using selection sort
{
for i:=1 to n do
{
j:=i;
for k:=i+1 to n do
{
if(a[k]<a[j]) then j:=k;
}
t:=a[i];
a[i]:=a[j];
a[j]:=a[t];
}
}

Example 4: Algorithm Sort(a,n)


// Sort elements in ascending order
{
for i:=1 to n do
for j:=i+1 to n-1 do
{
if(a[i]>a[j]) then
{
temp:=a[i];
a[i]:=a[j];
a[j]:=temp;
}
}
}

More Examples do it : Multiplication of two matrices, addition of two matrices, Fibonacci,


factorial, GCD, reverse of a number etc discussed in running notes
Recursive Algorithm: A recursive function is a function that is defined in terms of itself.
Similarly, an algorithm is said to be recursive if the same algorithm is invoked in the body.
An algorithm that calls itself is Direct Recursive. If it calls another algorithm then indirect
recursive.

Example: Algorithm Towers of Hanoi (n,x,y,z)


// Move top n disks from tower x to tower y
{
if(n>=1) then
{
Towers of Hanoi(n-1,x,z,y);
write(“Top disk x to y”)
Towers of Hanoi (n-1,z,y,x);
}
}

Example: Algorithm factorial(n)


// Factorial using recursion
{
if(n:=1) then
return 1;
else
return n*factorial(n-1);
}

Example: Algorithm Perm (a,k,n)


{
if(k==n) then
write(a[1:n]); //output permutation
else //a[k:n] has more than one permutation
//generate this recursively
for i:=k to n do
{
t:=a[k];
a[k]:=a[i];
a[i]:=t;
Perm(a,k+1,n);
t:=a[k];
a[k]:=a[i];
a[i]:=t;
}
}
Difference between Algorithm and Pseudo code:
 Algorithm is a well defined sequence of steps that provide a solution for a given
problem.
 Pseudo code is one of the methods that can be used to represent an algorithm.
 Algorithms can be written in natural Language.
 Pseudo code is written in a format that is closely related to high level programming
language structures
 Pseudo code does not use specific programming language syntax and therefore could
be understood by programmer‟s who are familiar with different programming
language.
 Transforming an algorithm presented in pseudo code to programming code could be
much easier than converting an algorithm written in natural language.

Performance Analysis: Algorithm evaluation can be done in two ways either before
execution of a program or after execution of a program

Priori Estimate (Performance Analysis) - [before execution of a


program]
Posteriori Estimate (Performance Measurement) - [after execution of a
program]

Efficiency of an algorithm can be done by measuring the performance of algorithm.


Performance Analysis mainly deals with two factors

Space Complexity: The space complexity of an algorithm is the amount of memory it


needs to run to completion.
Time Complexity: The Time complexity of an algorithm is the amount of computer
time it needs to run to completion.

Performance Analysis also deals with other factors like

Measuring Input Range


Measuring run time
Computing order of growth of an algorithm
Computing best case, worst case and average case.

Space Complexity: It is defined as amount of memory required by an algorithm to


run. Two factors are used to compute space complexity

Fixed Part: Independent of input and output characteristics. It includes


instruction space, Space for variables, Space for constants and so on.

Variable Part: It is also called as dynamic part that consists of space


needed by variable whose size is dependent on problem instance at
runtime. It includes Space needed by reference variables, Recursion
stack space and so on.
Let P be an algorithm, then total space required for algorithm is S(P)=C+Sp

Where C is constant which is fixed space and Sp is variable space which varies
depend on the problem

When we analyze space complexity of an algorithm, we concentrate on estimating


Sp(Variable Space)

Example: Algorithm sum(a,n)


//adding elements in array
{
s:=0;
for i:=1 to n
s:=s+a[i];
return s;
}

Space needed for this algorithm as follows:


Sum variable„s‟ – 1 word
Loop Variable „i‟ - 1 word total size = n+3 words
Size variable „n‟ – 1 word
Array „a‟ values – n words

Example: Algorithm Rsum(a,n):


// Addition of elements using recursion
{
if(n<=0) then return 0;
else
return Rsum(a,n)+a[n];
}

Space needed for this algorithm as follows:


Return address (Rsum) - 1 word
Pointer to „a‟ - 1 word total size=3 words
Local variable „n‟ - 1 word total space=3(n+1)
Depth of Recursion - n+1 words

Time Complexity: The amount of time required by an algorithm to complete its


execution. Two factors are used to compute time complexity.
Compile Time: Does not depend on instance characteristics
Run Time: Depend on particular problem instance
Let P be an algorithm, then total time required for algorithm is T(P)=C+Tp, Where c
is compile time and Tp is runtime
Time depends on several other factors like
 System Load
 Number of programs that are running
 Instruction set used
 Speed of underlying hardware
Because of these reasons the time complexity is calculated by using frequency count
that is number of times each instruction is executed.
One of the easiest methods to calculate time complexity is counting the number of
steps.
We can determine the number of steps needed by a program to solve a particular
problem instance in one of two ways
 In the First method, introduce a new variable count into the program. This is a
global variable with initial value „0‟.
 The Second method to determine the step count of an algorithm is to build a
table in which we list the total number of steps contributed by each statement.

Example: First Method


Algorithm sum(a,n)
{
sum:=0;
count:=count+1; // Count is global, initially zero
for i:=1 to n do
{
count:=count+1; // for for i:=1 to n(true condition)
sum:=sum+a[i];
count:=count+1; // for assignment
} count:=count+1; // last time for (false condition)
return sum;
count:=count+1; // for return stmt
}
Time complexity: inner loop – count=2n total 2n+3 frequency count: Ɵ(n)
Remaining – count=3

Second Method
StatementNum Statement Steps per execution Frequency Total steps
1 Algorithm sum(a,n) 0 - 0
2 { 0 - 0
3 sum:=0; 1 1 1
4 for i:=1 to n 1 n+1 n+1
5 sum:=sum+a[i] 1 n n
6 return sum; 1 1 1
7 } 0 - 0
Total Steps for algorithm 2n+3

Time complexity frequency count: Ɵ(n)


Examples: Matrix Addition: 2n2+2n+1 O(n2) , Matrix multiplication: 2n3+3n2+2n+1 O(n3)
Algorithm Fibonacci (a,b,c,n)
{
a:=0;
b:=1;
write(a,b);
for i:=2 to n step 1 do
{
c:=a+b; Time complexity: 5n-1 Frequency Count: O(n)
a:=b;
b:=c;
write(c);
}
}

First Method:
Algorithm Rsum(a,n):
// Addition of elements using recursion
{
count:=count+1; // for if condition
if(n<=0) then
count:=count+1; // for return stmt
return 0;
else
return Rsum(a,n)+a[n]; // for addition, function invocation and return
}
Time Complexity: 2(for n=0)+ TRsum(n-1)
2+TRsum(n-1) => 2+2+TRsum(n-2) …….. n(2)+TRsum(0) => 2n+2 n>0

Second Method:
StatementNum Statement Steps per execution Frequency Total steps
n=0 n>0 n=0 n>0
1 Algorithm Rsum(a,n): 0 - - 0 0
2 { 0 - - 0 0
3 if(n<=0) then 1 1 1 1 1
4 return 0; 1 1 0 1 0
5 else 0 - - 0 0
6 return Rsum(a,n)+a[n]; 1+x 0 1 0 1+x
7 } 0 - - 0 0

Total Steps for algorithm 2 2+x

T(n)= 2 for n=0


T(n)=2+T(n-1) for n>0 => 2n+2 for (n>0) Frequency count: O(n)
Asymptotic Notations: To choose the best algorithm, we need to check the efficiency of
each algorithm. The efficiency can be measured by computing the space and time
complexities. Commonly used asymptotic notations are:
 Big O notation (Upper Bound)
 Omega Notation (Lower Bound)
 Theta Notation ( Tight Bound)
By using these notations we can give time complexities as
o Big O – Worst Case
o Omega – Best Case
o Theta – Average Case
Big O Notation: It is denoted by „O‟. It is a method of representing the upper bound
of an algorithm that is worst case time complexity of an algorithm.
Definition: A function Let f(n) and g(n) be two non-negative functions and Let n0,nc
are two integers such that the value of input „n‟ is greater than n0(n>n0). Similarly „c‟
is a constant which must be greater than zero(c>0), then we define the function as
follows
If f(n) ≤ c*g(n) then f(n)=O(g(n)))

 Consider f(n)=2n+2, g(n)=n2 so that f(n) < c*g(n) by using mathematical induction
 Show that the time complexity of 3n2+4n-2 is O(n2)
 Remaining problems see running notes

Big Omega Notation: It is denoted by Ώ. This notation is used to represent the lower
bound of algorithm runtime that is best case time complexity.
Definition: A function f(n) is said to be Ώ(g(n)) if f(n) is bounded below by some
positive constant multiple of g(n) such that f(n)≥ c*g(n)
If f(n)≥ c*g(n) then f(n)= Ώ(g(n))
Consider f(n)=2n2+5, g(n)=7n show that f(n)= Ώ(g(n))

Theta Notation: It is denoted by Ɵ. By this method the running time is between


upper bound and lower bound.
Definition: Let f(n) and g(n) be two non-negative functions and consider two positive
numbers c1 and c2 such that c1*g(n)<f(n)< c2*g(n) then f(n)=Ɵ(g(n))

 Consider two functions f(n)=2n+2, g(n)=n find the value of c1 and c2


 Find the theta notation for following function f(n)=3n2+5n+2 , g(n)=n2

Little o notation: if f(n)=O(g(n))) and f(n)≠Ɵ(g(n)) then f(n)=o(g(n))


Little Omega notation: if f(n)= Ώ(g(n))and f(n)≠Ɵ(g(n)) then f(n)=ω(g(n))

Practical Complexities:
Time complexity of an algorithm is generally some function of the instance
characteristics.
This function is very useful in determining how the time requirements vary as the
instance characteristics change.
The complexity function can also be used to compare two algorithms P and Q that
perform the same task.
Assume that algorithm P has complexity Ɵ(n) and algorithm Q has complexity Ɵ(n2).
We can assert that algorithm P is faster than algorithm Q for sufficiently large n by
seeing polynomial of high degree.
How the various functions grow with „n‟. See the below table and figure.

By seeing the above figure we can say that the function 2n grows very rapidly with n.
Amortized Analysis:
Amortized Analysis means finding average running time per operation over a worst
case sequence of operations.
An Amortized analysis indicates that average cost of a single operation is small if
average of sequence of operations is obtained.
There is a difference between amortized and average case analysis. In average case
analysis, averaging over all possible inputs but in amortized analysis, averaging over a
sequence of operations.
Suppose that a sequence of operations I1, I2, D1, I3, I4, I5, I6, D2, I7 of insert and
delete operations are performed on set. Assume the actual cost of each seven inserts
takes 1 unit of time and delete operations D1 and D2 takes 8 and 10 respectively.
Total Actual Cost=7+8+10=25
In amortization scheme, charge some actual cost of operations to other operations.
This reduces cost of one operation and reduces cost of other operations.
If we charge cost of one unit for each insertion (I1 to I6) from delete operation then
D1=6, D2=6.
The two units of D1 is transferred to I1, I2 that is I1=2, I2=2 and 4 units of D2 is
transferred that is I3=2, I4=2, I5=2, I6=2, lastly I7=1.
Total Amortized Cost of I1, I2, D1, I3, I4, I5, I6, D2, I7 = 2+2+6+2+2+2+2++6+1=25
that is amortized cost equal to actual cost. In general amortized cost greater than or
equal to sum of their actual cost
There are three commonly used techniques used in amortized analysis:
 Aggregate Analysis
 Accounting Method
 Potential Method
 Aggregate Analysis: It is similar to average case analysis but we consider the
average for worst case sequence.
In aggregate analysis, if sequence of „n‟ operations takes worst case time T(n)
in total. In that worst case, the average cost or amortized cost per operation is T(n)/n
Amortized cost > Actual cost
Potential function p(i)=Amortization cost (i) – Actual cost(i) + p(i-1)
P(n) - P(0) > 0
Example 1: In Jan, you buy a new car from a dealer who offers you the following
maintenance contract $50 each month other than March, June, September and December,
$100 every March, June and September and $200 every December.
Worst Case Method: $50- Jan,Feb,Apr,May,Jul,Aug,Oct,Nov
$100- Mar,Jun,Sep
$200- Dec
Aggregate Method: To use aggregate method for amortized complexity, we first determine
an upper bound on the sum of the costs for the first „n‟ months. As tight a bound as is
possible is desired.
The sum of the actual monthly costs of the contract for the first „n‟ months is
(50*8)+(100*3)+(200)=400+300+200=900/12=75
MONTH 1 2 3 4 5 6 7 8 9 10 11 12
Actual Cost 50 50 100 50 50 100 50 50 100 50 50 200
Amortized Cost 75 75 75 75 75 75 75 75 75 75 75 75
P(i) 25 50 25 50 75 50 75 100 75 100 125 0

Example 2: Implementing Stacks on Array


Two fundamental operations takes O(1) time – (push, pop) Since each of these
operations runs in O(1) time. The total cost of a sequence „n‟ push and pop operation is O(n).
Now, we add other operation MULTIPOP(S, K) which remove K top objects of stack
S.
MULTIPOP(S, K)
While not STACK = EMPTY(S) and K>0
pop(S)
K=K-1
Average Cost of an operation is O(n)/n = O(1). Therefore, all three stack operations have an
amortized cost O(1).

 Accounting Method: Accounting method is performed based on the charges that we


are assigning to the operation. The idea of accounting method as follows:
 Assign different charges to different operations.
 Amount of charge is called amortized cost.
 There will be actual cost which will define the nature of the algorithm.
 Amortization cost can be less than or greater than actual cost.
 When it is greater than actual cost, the difference is saved in an object called
credit
 If it is less than actual cost, the stored credits are used.
 In Accounting method, amortized cost = actual cost + credit.
Example 1:
MONTH 1 2 3 4 5 6 7 8 9 10 11 12
Actual Cost 50 50 100 50 50 100 50 50 100 50 50 200
Amortized Cost 70 70 70 70 70 70 70 70 70 70 70 70
P(i) 20 40 10 30 50 20 40 60 30 50 70 -60

p(i)=Amortization cost (i) – Actual cost(i) + p(i-1)


P(n) - P(0) > 0
P(i)=-60<0 , condition failed
Invalid Amortization Cost (70). Again assume amortized cost as 80 and do the calculation

Example 2: Implementing Stacks on Array


Consider Push and pop operation
Push: top=max-1 pop: item=a[top]
top++ top--
a[top]=item
Let the actual cost required to perform either push or pop operation is 1. Let us assume
amortization cost push=2 and pop=0 then
For push: Credit= Amortization cost – Actual cost
=2-1 = 1
For pop: Credit= Amortization cost – Actual cost
=0-1 = -1

 Potential Method: This method is similar to accounting method in which the concept
the prepay is used. In this method there will be no credit but there will be some
potential difference or energy which can be used to pay for future operations. Instead
of associating potential with specific object, it is associated with whole data structure.
Working of Potential Method: Let D0 be the initial data structure for „n‟ operations.
We have data structure D0 to Dn and then actual cost has C1…Cn. Potential function is
denoted by Ø then
Amortization cost = actual cost + potential difference
n n
|
∑ Ci = ∑ Ci+[Ø(Dn) – Ø(D0)]
i=1 i=1

Example: Consider a stack of size „S‟ then initial charge be „S‟.


 if a push operation is performed on stack then the potential function
Ø(Dn) = S+1
 If a pop operation is perform on stack then potential function Ø(Dn) = S-1
 Potential difference for push operation is Ø(Dn) - Ø(D0) =S+1-S = 1
 Potential difference for pop operation is Ø(Dn) - Ø(D0) =S-1-S = -1
 Amortization cost for push and pop is
Amortization cost = actual cost + potential difference
= 1+1 = 2
Amortization cost = actual cost + potential difference
= 1-1 = 0
Example: Amortized cost = actual cost + P(1)-P(0) = 50+25-0=75
= actual cost + P(2)-P(1) = 50+50-25=75
= actual cost + P(3)-P(2) = 100+25-50=75
:
:
:
Calculate all costs (Maintenance car)

 Note: Amortized analysis is used for algorithms where an occasional operation is very
slow but most of the other operations are faster.
In Amortized analysis, we analyze a sequence of operations and guarantee a
worst case average time which is lower than the worst case time of a particular
expensive operation.
Performance Measurement:
Performance evaluation can be done in two ways. Before the execution of a program
called Performance Analysis and after the execution of a program called Performance
Measurement.
Performance Measurement is concerned with obtaining the space and time
requirements of a particular algorithm.
These quantities depend on the compiler and options used as well as on a computer on
which the algorithm is run.
To obtain computing or run time of a program we need clocking procedure that
returns the current time in milliseconds.
Time complexity can be calculated with the help of any programming language like
C, C++, Java and Python.
In C language, the time events are stores in standard library #include<time.h> and use
GetTime() to get current time in milliseconds.
In Java language, the time events are stores in package java.util.Date and use
getTime() to get current time in milliseconds.
In Python language, the time events are stores in package time and use time.time() to
get current time in milliseconds.
Performance Measurement can be calculated by subtracting start time from current
time that is performance measurement=current time - start time
Suppose we wish to measure the worst case performance of the sequential search
algorithm. First, we need to decide the values of n for which the times are to be
obtained and then determine for each of the above values of n, the data that exhibit the
worst case behavior.
Algorithm SeqSearch(a,x,n)
{
i:=n;
a[0]:=x;
while(a[i]!=x) do
i:=i-1;
return i;
}
In the worst case, to search for x, given the size n of a. An asymptotic analysis reveals
that this time is ϴ(n). So, we expect a plot of the times to be a straight line.
To measure the computing time of this algorithm we need to write a TimeSeqSearch
algorithm, in that GetTime() is used to get the current time and start time of algorithm
in milliseconds.
Finally, performance measurement of an algorithm can be done in milliseconds.
Algorithm TimeSeqSearch(a,x,n)
{
h:=GetTime();
i:=n;
a[0]:=x;
while(a[i]!=x) do
i:=i-1;
return i;
h1:=GetTime();
t:=h1-h;
write(t);
}
Now we are writing an algorithm to measure the time in milliseconds for „n‟ different
values.
Algorithm TimeSearch()
{
for j:=1 to 1000 do
{
a[j]:=j;
}
for j:=1 to 10 do
{
n[j]:=10*(j-1);
n[j+10]:=100*j;
}
for j:=1 to 20 do
{
h:=GetTime();
k:=SeqSearch(a,0,n[j]);
h1:=GetTime();
t:=h1-h;
write(n[j],t);
}
}
Timing results of above algorithm in milliseconds are

The times obtained are too small to be of any use to us. Most of the times are zero,
this indicates that precision of our clock is inadequate. The nonzero times are just
noise and are not representative of the time taken.
To time a short event, it is necessary to repeat it several times and divide the total time
for the event by the number of repetitions
Algorithm TimeSearch()
{
// Repetition factors
r[21]:={0, 200000, 200000, 150000, 100000, 100000, 100000, 50000,
50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000, 50000,
25000, 25000, 25000, 25000}
for j:=1 to 1000 do
{
a[j]:=j;
}
for j:=1 to 10 do
{
n[j]:=10*(j-1);
n[j+10]:=100*j;
}
for j:=1 to 20 do
{
h:=GetTime();
for i:=1 to r[j]do
{
k:=SeqSearch(a,0,n[j]);
}
h1:=GetTime();
t1:=h1-h;
t:=t1;
t:=t/r[j];
write(n[j],t1,t);
}
}
Timing results and graph of above algorithm in milliseconds are
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner
Scanned by CamScanner

You might also like