Pseudocode 1 Algorithm 1 array MaxA n Input

  • Slides: 8
Download presentation
Pseudo-code 1 Algorithm 1 array. Max(A, n) Input array A of n integers Output

Pseudo-code 1 Algorithm 1 array. Max(A, n) Input array A of n integers Output maximum element of A current. Max A[0] for i 1 to n 1 do if A[i] current. Max then current. Max A[i] return current. Max l Running time of algorithm is O(n)

Pseudo-code 2 Algorithm 2 prefix. Averages(A, n) Input array A of n integers Output

Pseudo-code 2 Algorithm 2 prefix. Averages(A, n) Input array A of n integers Output array X of n doubles Let X be an array of n doubles for i 1 to n 1 do a 0 for j 0 to i 1 do a a + A[j] X[i] a / (i+1) return X l Running time of algorithm is O(n 2)

Pseudo-code 3 Algorithm 3 m 1 result 0 for i 1 to n do

Pseudo-code 3 Algorithm 3 m 1 result 0 for i 1 to n do m m*2 for j 1 to m do result + i*m*j return result l Running time of algorithm is O(2 n)

Recursive algorithm analysis: factorial Factorial(n) if(n==1) return 1 else return Factorial(n-1)*n l 1 st

Recursive algorithm analysis: factorial Factorial(n) if(n==1) return 1 else return Factorial(n-1)*n l 1 st step: come up with a recurrence equation l T(n) = running time of Factorial(n) l l => T(n) = T(n-1) + 1 2 nd step: identify a base case l That is, a termination condition (n=1) l T(1) = 1 step (i. e. , a constant number of steps being executed)

Recursive algorithm analysis: factorial (cont’d) l 3 rd step: expand T(n) l 4 th

Recursive algorithm analysis: factorial (cont’d) l 3 rd step: expand T(n) l 4 th step: see the pattern

Binary search recursion: pseudo-code Boolean BS(A, key, start, end) mid = (start+end)/2 if(A[mid] ==

Binary search recursion: pseudo-code Boolean BS(A, key, start, end) mid = (start+end)/2 if(A[mid] == key) return true else if(end <= start) return false else if (A[mid] > key) return BS(A, key, start, mid-1) else return BS(A, key, mid+1, end)

Binary search recursion: running time analysis l 1 st step: find recurrence equation l

Binary search recursion: running time analysis l 1 st step: find recurrence equation l T(n): running time of BS for input A of size n l l T(n) = T(n/2) + 1 2 nd step: look at termination condition l When the search pool is reduced to one l T(1) = 1

Binary search recursion: running time analysis (cont’d) l 3 rd step: expand T(n) l

Binary search recursion: running time analysis (cont’d) l 3 rd step: expand T(n) l 4 th step: pattern matching