4. Algorithm analyzing (Complexity) :
1.Time : Analysis of the time required to solve a problem of a particular size
2.Space: Analysis of the computer memory required to solve a problem of a particular size
5. Algorithm analyzing (Complexity) :
•We care about degree of algorithm
•To determine the degree of algorithm we need to determine all the basic operation that take the longest time to execute.
•We think always in the worst case.
6. Algorithm analyzing (Complexity) :
•Example:imagine we have array with (n) element and we search for element (k) inside it.
•Best case : we find our value (k) in first cell ( that mean we need just one compare operation )
7. Algorithm analyzing (Complexity) :
•Worst case : we find our value [k]in the last position or we don’t find it ( that’s mean we need [n]compare operation ).
•Average case : is to find our value [k] in middle the array
11. Alg.
Who_knows(){
arr: array [1..n] of integer;
res : integer; res = 0;
For i=0 To ndo
res = res +arr[i];
}
1. We have just one operation [+]
2. We know that we need to loop ntimes
3. What about
푖=1 푛 1=푛
4. Complexity is O(n)
12. Alg.
Who_knows(){
arr: array [1..n] of integer;
res : integer; res = 0;
sub : integer; sub = 10000;
For i=0 To ndo
res = res +arr[i];
sub = sub –arr[i]
}
1. We have just tow operation [+,-]
2. We know that we need to loop ntimes
3. What about
푖=1 푛 2=2∗ 푖=1 푛 1=2푛
The cost will be 2n !!! But we care about degree , so it’s just O(n).
13. Alg.
Never_mind(){
arr: array [1..n,1..m] of integer;
res : integer; res = 0;
For I =0 To ndo
For j =0 To mdo
res = res +arr[i,j];
}
1. We have just one operation [+]
2. Nested loops !! That’s mean we need to loop n*m times
3. What about
푖=1 푛 푗=1 푚 1=(푛∗푚)
The cost will be n*m!!! Let’s consider that m=n so the cost will be O(푛2)
14. Alg.
Never_mind(){
For I =0 To ndo
For j =0 To mdo
For k =0 Toj do
res = res + 1;
}
1. We have just one operation [+]
2. Nested loops !!
3. What about
푖=1 푛 푗=1 푚 푘=1 푗 1= 푖=1 푛 푗=1 푚 푗
= 푖=1 푛푛(푛+1) 2= 푛(푛+1) 2 푖=1 푛1= 푛2(푛+1) 2
Complexity is O(푛3)
15.
16. Algo.
NeverAsk( ) {
s = 1;
while ( n > 1 ) {
s = s * n;
n = n/2 ;
}
}
What’s the cost ??!!
17. Let’s consider n = 16
At [1] execution, N got N/2,
At [2] execution, N got N/4
At [3]execution, N got N/8
At [4]execution, N got N/16
At last execution 푁 2푘> 0 푁 22= 1 n = 2푘k =푙표푔2(푛)
In general O(푙표푔푛(푛))
Times
1
2
3
..
k
N 푁 2 푁 22 푁 23 푁 2푘
20. What if we have a condition
•First let’s type the formula
푖=1 푛2||푖푚표푑푛 푗=1 푖 1
•Then we retype the condition
i= k*n ; where k is constant
•When i= 푛2, k = 푛2 푛 =푛
푘=1 푛 푗=1 푘∗푛 1= 푘=1 푛 푘∗푛=푛∗ 푛(푛+1) 2
Complexity is O(푛3)