Step Count Method in Algorithm
Step Count Method in Algorithm
seqSearch(arr, n, key) 0 0 0 c1
i := 0 1 1 1 c2
while i < n, do n+1 1 n+1 c3
if arr[i] = key, then n 1 n c4
break
end if
i=i+1 n+1 1 n+1 c5
done 0 1 0 c6
return i
Total Cost = c2 + c3(n+1) + c4 (n) + c5 (n+1)
= c2 + 8 c3 + 7 c4 +8 c5 = value Time Complexity
Code SC FC Cost
float sum( float list[], int n) 0 0 1
{
float sum = 0; 1 1 1
int i;
for (i=0; i<n; i++) 1 n+1 1
sum = sum + list[i]; 1 n 1
return sum; 1 1 1
}
list n=3
40 23 67
0 1 2 3
I =3 sum = 130.0
FREQUENCY COUNT:
Number of times each statement is executed
For a non-executable statement frequency count is 0
SC * FC = Total steps for each statement
Algorithm reverse(a):
for i = 0 to n/2
swap a[i] and a[n-i-1]
In the above two simple algorithms, you saw how a single problem can have
many solutions. While the first solution required a loop which will execute
for n number of times, the second solution used a mathematical operator * to
return the result in one line. So which one is the better approach, of course the
second one.