DAA Introduction - Cont...
DAA Introduction - Cont...
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
M(1) = 1
Recurrence
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