Iterative Algorithms
1. Statement
1.1 Rule
The cost of a statement is:
- if it is an elementary statement
- Otherwise, it is a subroutine. The cost of the statement is the subroutine's cost.
1.2 Example 1
a=5
The cost of this statement is
1.3 Example 2
A=[(77*i+13)%59 for i in range(n)]
A.sort()
- Cost of the first statement is as it creates an array of size
- Cost of the second statement is the cost of the
sort
method on
2. Branching
2.1 Rule
The cost of a conditional statement is the cost of the executed path.
When in doubt, we can bound all paths from above by where the cost of the path
2.2 Example
R=0
if x==0:
for i in range(n):
for j in range(n):
R+=i*j
else:
for i in range(n):
R+=i
- If we know that , then the complexity is
- If we know that , then the complexity is
- If we have know no information on , then we will estimate the complexity using
3. Loops
3.1 Rule
We will suppose that we will iterate over a multiset
Let be the cost of the body of the loop as a function of the loop variable .
The cost of the loop is then:
3.2 Example 1
R=0
for i in range(n):
R+=5
The complexity of this algorithm is:
3.3 Example 2
R=0
while n > 0:
R+=n
n=n//2
We have
We have and
So the complexity of the algorithm is:
3.4 Example 3
k=1
R=0
while n//k > 0:
for j in range(n//k):
R+=1
k*=2
3.4.1 Outer Loop
This is an example of a nested loop.
is the iterated values of the outer loop
We have
3.4.2 Inner Loop
Let is the cost of the inner loop
We have
The complexity of the inner loop is:
3.4.3 Complexity of the Algorithm
We have:
So the algorithm is
3.5 Example 4
for i in range(42):
for j in range(3):
for k in range(n):
for s in range(r):
break
if k>math.sqrt(n):
break
The complexity of such algorithm is: