Algorithm and Problem-Solving
Algorithm and Problem-Solving
of Algorithms
Objectives 1
• Algorithm • Program
▪ Design Phase ▪ Implementation Phase
▪ Natural Language ▪ Any Programming Language
▪ Domain Knowledge ▪ Programmer
▪ OS and H/S Independent ▪ OS and H/S Dependent
▪ Analyze ▪ Testing
Example 1: Write an algorithm, a pseudo-code and draw a flowchart that will read the two sides of a
rectangle and calculate its area.
Example 2: Write an algorithm and draw a flowchart that will read the two numbers and find its largest
number.
end
Algorithm Analysis 11
• Time complexity
▪ is the amount of CPU time it needs to run to completion.
• Space complexity
▪ is the amount of memory it needs to run to completion.
• Power consumption
• Network consumption
• Computational resource
Asymptotic Notations 12
Example : Write a program that takes two numbers as input, swaps them.
Iteration i
Assume :
Algorithm() 1 1
i ≥ n : terminate point
{ 2 1*2 = 21 i = 2k
for(i=1; i < n; i = i * 2) 3 21*2 = 22
{ → 2k ≥ n
4 22*2 = 23
staments; 2k = n
} - -
- -
k = Log2n
}
n 2k Time Complexity = O(Log2n)
Square Root Time O( 𝒏) Complexity 16
Assume :
Algorithm() Iteration i p p > n : terminate point
{ 1 1 0+1 = 1 𝑘(𝑘+1)
p=
2
p = 0; 2 2 1+2 = 3
for(i=1; p <= n; i++) 𝑘(𝑘+1)
3 3 1+2+3 → >n
{ 2
p = p + i; 4 4 1+2+3+4 𝑘 2 +𝑘
} >n
- - - 2
return p; - - - 𝑘2 > n
} n k 1+2+3+…+k
k= 𝑛
Time Complexity = O( 𝑛)
Linear Time O(n) Complexity 17
Example : Write a program that finds the sum of all the numbers in an array.
Algorithm Sum(arr, n)
{ Statement Count Variable Count
sum = 0; sum = 0; 1 arr n
for( i = 0; i < n; i++) for( i = 0; i < n; i++) n+1 n 1
{ sum = sum + arr[i]; n sum 1
sum = sum + arr[i]; return sum; 1 i 1
} T(n) 2n + 3 S(n) n+3
return sum; Time O(n) Space O(n)
}
Log-Linear Time 𝑂(𝑛 log 𝑛) Complexity 18
Algorithm()
{
for( i = 0; i < n; i++) Statement Count
{ for( i = 0; i < n; i++) n+1
for(j=1; j < n; j = j*2) for(j=1; j < n; j = j*2) n * log n
{ staments; n * log n
staments; T(n) 2n log n + n
} Time O(n log n)
}
}
Quadratic Time O(n2) Complexity 19
n=4
Algorithm Fib(n)
{ Fib(1)
if( n == 0) { Fib(2)
return 0; Fib(3) Fib(0)
}
Fib(1)
if( n == 1) {
return 1; Fib(4)
}
Fib(1)
return Fib(n-1) + Fib(n-2);
Fib(2)
}
Fib(0)
Time : O(2n)
Factorial Time 𝑂(𝑛!) Complexity 22
0
Fun(1) Fun(0) statements;
0
n=3 0
Algorithm Fun(n) Fun(2) Fun(1) Fun(0) statements;
1
{
0
if( n == 0) { 0
statements; 0 Fun(1) Fun(0) statements;
1
} Fun(3) Fun(2)
0
for( i = 0; i < n; i++) { 1 Fun(1) Fun(0) statements;
Fun(n – 1);
2
} 0 0
} Fun(2) Fun(1) Fun(0) statements;
1 0
Fun(1) Fun(0) statements;
Printed Statement → 6 = 3! = n!
Time : O(n!)
Further Work 23