Professional Documents
Culture Documents
Lecture 3. DAA
Lecture 3. DAA
Lecture 3. DAA
S(P) = c + Sp
Example #1
Algorithm abc(a,b,c)
{
return a+b+b*c+(a-c)/(a+b) +2.0;
}
Example #1
Algorithm abc(a,b,c)
{
return a+b+b*c+(a-c)/(a+b) +2.0;
}
S(P) = c + Sp
Sp = 0
Example #2
Algorithm sum(a,n)
{
s = 0.0;
for i:=1 to n do
s:=s+a[i];
return s;
}
Example #2
Algorithm sum(a,n)
{
s = 0.0;
for i:=1 to n do
s:=s+a[i];
return s;
}
s(n) >= n+3
n for a[ ] , one for each n,i,s
Example #3
algorithm rsum (a,n)
{
if (n<=0) then return 0.0
else
return rsum(a,n-1)+a[n];
}
Example #3
algorithm rsum (a,n)
{
if (n<=0) then return 0.0
else
return rsum(a,n-1)+a[n];
}
• Instance characterized by n
• Recursive stack space required at each level
•(n, return address,*a[]) 3 words
• Depth of recursion considering first invocation - (n+1)
• S(n) >= 3*(n+1)
Time Complexity
• Initialization instructions
• Loops.
– Number of passes of the loops
• Count the basic operations/steps
Basic Steps - Example
• Search
– Basic operation is compare x and y
• Matrix multiplication
– Basic operation is multiplication of real numbers
Counting Steps
Recursive formula
Example 3
algorithm add(a,b,b,m,n)
{
for i:=1 to m do
for j:=1 to n do
c[i,j]:=a[i,j]+b[i,j];
}
Example 3
algorithm add(a,b,b,m,n)
{ Count = count + 1 // For the i loop
for i:=1 to m do
{ count = count +1 //For the j loop
for j:=1 to n do
{ count = count + 1 //For the ij loop
c[i,j]:=a[i,j]+b[i,j];
} count = count + 1 //for the last time of j loop
}
count =count + 1 //for the last time of i loop
}
Example 3
algorithm add(a,b,b,m,n)
{ Count = count + 1 // For the i loop
for i:=1 to m do
{ count = count +1 //For the j loop
for j:=1 to n do
{ count = count + 1 //For the ij loop
c[i,j]:=a[i,j]+b[i,j];
} count = count + 1 //for the last time of j loop
}
count =count + 1 //for the last time of i loop
}
Example 3
algorithm add(a,b,b,m,n)
{ Count = count + 1 // For the i loop
for i:=1 to m do
{ count = count +1 //For the j loop
for j:=1 to n do
{ count = count + 1 //For the ij loop
c[i,j]:=a[i,j]+b[i,j];
} count = count + 1 //for the last time of j loop
}
count =count + 1 //for the last time of i loop
} m + mn + mn + m + 1 = 2mn + 2m + 1
Computing Step Count from s/e
• Each statement will have an (s/e) steps/execution
depending on the type of statement
• Frequency of each statement is multiplied with the
corresponding s/e of that statement to get the step count
for that statement.
• Statement Step counts are added to give the total count
Example 1