Analysis of Algorithm
Analysis of Algorithm
STRUCTURES
AND
ALGORITHMS
Hafiz Ahsan Arshad
1. Initialize two integer variables, x and y, to 0.
2. Start an outer loop with i ranging from 0 to 2 (inclusive).
• Inside the outer loop, start an inner loop with j
ranging from 0 to 2 (inclusive).
• Check if j is even.
• If j is even, increment the value of x by 2.
• If j is odd (not even), increment the value of y by 4.
• End the inner loop.
3. End the outer loop.
4. Print the final values of x and y to the console.
What is Algorithm
High Level
Language
Program
Properties of Algorithms
■ It now follows that using this scheme, the distance driven by the driver to deliver
the packages is:
1+1+1+...+1 = 50 miles
■ Therefore, the total distance traveled by the driver to deliver the packages and
then getting back to the shop is:
50+50 = 100 miles
Example of Efficiency of
Algorithm (Cont…)
■ Another driver has a similar route to deliver another set of 50 packages. The
driver looks at the route and delivers the packages as follows:
■ The driver picks up the first package, drives one mile to the first house,
delivers the package, and then comes back to the shop. Next, the driver picks
up the second package, drives 2 miles, delivers the second package, and then
returns to the shop. And so on. Figure 1-3 illustrates this delivery scheme.
■ The driver delivers only one package at a time. After delivering a package, the
driver comes back to the shop to pick up and deliver the second package.
Using this scheme, the total distance traveled by this driver to deliver the
packages and then getting back to the store is:
2 * (1+2+3+...+50) = 2550 miles
Example of Efficiency of
Algorithm (Cont…)
■ Now suppose that there are n packages to be delivered to n houses,
and each house is one mile apart from each other, as shown in Figure
1-1.
■ If the packages are delivered using the first scheme, the following
equation gives the total distance traveled:
(1-1)
■ If the packages are delivered using the second method, the distance
traveled is:
2* (1+2+3+ ... + n) = 2 * () = + n (1-2)
Gauss Formula:
Sum from 1 to n =
Efficiency of Algorithm (Cont…)
Block #1 t1
f (n) =
Block #2 t2 max(t1,t2)
f (n)= 1+max(4,3) = 5
Complexity of Algorithms
2k*2 = 2
k+1
Compare Type of Time
Function