Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Departemnent of Computer Sciences 1/3 Semester Spring 2016

CSL-221: Data Structures & Algorithms Lab 02: Time Complexity

LAB Measurement of Time Complexity of an algorithm

02
Objective(s): Upon completion of this lab session, Student will be able to
understand the following concepts
1 Analysis of an algorithm
2 Time Complexity
3 Difference between two algorithms

LabTask(s):

Write programs for following two different algorithm for finding that given number is
1 prime or not

Frist Algorithm Second Algorithm


for i  2 to n-1 for i  2 to √n
if i divides n if i divides n
n is not prime number n is not prime number

2 Calculate times taken by these program for given values and conclude which
algorithm is better than other
i. n = 11
ii. n = 101
iii. n=1000003
iv. n = 10000000019

Note: Let’s assume computer takes 1 mili-second for division operation. In the worst
case first algorithm loop will exactly (n-2) times or (n-2) division and in second
algorithm (√n – 1) times
LAB ACTIVITIES RELATED THEORY
Algorithms and Its Analysis

An algorithm is a finite set of precise instructions for performing a computation or for solving a
problem.
Departemnent of Computer Sciences 2/3 Semester Spring 2016
CSL-221: Data Structures & Algorithms Lab 02: Time Complexity

What is the goal of analysis of algorithms?


To compare algorithms mainly in terms of running time but also in terms of other factors (e.g.,
memory requirements, programmer's effort etc.)

Time Complexity
In computer science, the time complexity of an algorithm quantifies the amount of time taken
by an algorithm to run as a function of the length of the string representing the input
(Wikipedia)

Example:

50 packages delivered to 50 different houses


50 houses one mile apart, in the same area

Driver picks up all 50 packages


Drives one mile to first house, delivers first package
Drives another mile, delivers second package
Drives another mile, delivers third package, and so on
Distance driven to deliver packages
1+1+1+… +1 = 50 miles

Total distance traveled: 50 + 50 = 100 miles

Similar route to deliver another set of 50 packages


Driver picks up first package, drives one mile to the first house, delivers
package, returns to the shopDriver picks up second package, drives two miles,
delivers second package, returns to the shop

Example Continue…

Total distance traveled


2 * (1+2+3+…+50) = 2550 miles
Departemnent of Computer Sciences 3/3 Semester Spring 2016
CSL-221: Data Structures & Algorithms Lab 02: Time Complexity

n packages to deliver to n houses, each one mile apart

First scheme: total distance traveled


1+1+1+… +n = 2n miles
Function of n

Second scheme: total distance traveled


2 * (1+2+3+…+n) = 2*(n(n+1) / 2) = n2+n
Function of n2

--------------------------------------------------------------END-----------------------------------------------------------

You might also like