0% found this document useful (0 votes)
9 views10 pages

DAA Introduction - Cont...

The document discusses calculating complexity in both iterative and recursive programs, providing examples such as finding the maximum value in an array and matrix multiplication. It explains the recursive solution for the Towers of Hanoi problem and derives the complexity using recurrence relations. The emphasis is on understanding the accounting for basic operations in these algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

DAA Introduction - Cont...

The document discusses calculating complexity in both iterative and recursive programs, providing examples such as finding the maximum value in an array and matrix multiplication. It explains the recursive solution for the Towers of Hanoi problem and derives the complexity using recurrence relations. The emphasis is on understanding the accounting for basic operations in these algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Calculating complexity

Iterative programs

Recursive programs
Example 1
Maximum value in an array
function maxElement(A):
maxval = A[0]
for i = 1 to n-1:
if A[i] > maxval:
maxval = A[i]
return(maxval)
Example 2
Check if all elements in an array are distinct
functionnoDuplicates(A):
for i = 0 to n-1:
for j = i+1 to n-1:
if A[i] == A[j]:
return(False)
return(True)
Example 3
Matrix multiplication
functionmatrixMultiply(A,B):
for i = 0 to n-1:
for j = 0 to n-1:
C[i][j] = 0
for k = 0 to n-1:
C[i][j] = C[i][j] + A[i][k]*B[k][j]
return(C)
Example 4
Number of bits in binary representation of n
functionnumberOfBits(n):
count = 1
while n > 1:
count = count + 1
n = n div 2
return(count)
Example 5
Towers of Hanoi

Three pegs,
A, B, C

Move n disks
from A to B
Never put a larger disk above a smaller one

C is transit peg
Example 5
Recursive solution
Move n-1 disks from A to C, using B as transit peg

Move largest disk from A to B

Move n-1 disks from C to B, using A as transit peg


Example 5
Solve recurrence by repeated substitution
M(n) = number of moves to transfer n disks

M(n) = M(n-1) + 1 + M(n-1)

M(1) = 1

Recurrence

Recursive expression for M(n)


Example 5
Complexity

M(n) = 2M(n-1) + 1
= 2(2M(n-2)+1) + 1 = 22M(n-2) + (2+1)
= 22(2M(n-3)+1) + 2 + 1 = 23M(n-3) + (4+2+1)
=…
= 2kM(n-k) + (2k - 1)
=…
= 2n-1M(1) + (2n-1 - 1)
= 2n-1 + 2n-1 - 1 =
= 2n - 1
Summary
Iterative programs
Focus on loops

Recursive programs

Write and solve a recurrence

Will see more complicated examples

Need to be clear about “accounting” for basic


operations

You might also like