Download presentation
Presentation is loading. Please wait.
1
Pseudo-code 1 Running time of algorithm is O(n)
Algorithm1 arrayMax(A, n) Input array A of n integers Output maximum element of A currentMax A[0] for i 1 to n 1 do if A[i] currentMax then currentMax A[i] return currentMax A pseudo code is more structured than English prose and less detailed than a program. Moreover, it hides program design issues.
2
Pseudo-code 2 Running time of algorithm is O(n2)
Algorithm2 prefixAverages(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 A pseudo code is more structured than English prose and less detailed than a program. Moreover, it hides program design issues.
3
Pseudo-code 3 Running time of algorithm is O(2n) Algorithm3 m 1
result 0 for i 1 to n do m m * 2 for j 1 to m do result result + i*m*j return result A pseudo code is more structured than English prose and less detailed than a program. Moreover, it hides program design issues.
4
Recursive algorithm analysis: factorial
Factorial(n) if(n==1) return 1 else return Factorial(n-1)*n 1st step: come up with a recurrence equation T(n) = running time of Factorial(n) => T(n) = T(n-1) + 1 2nd step: identify a base case That is, a termination condition (n=1) T(1) = 1 step (i.e., a constant number of steps being executed)
5
Recursive algorithm analysis: factorial (cont’d)
3rd step: expand T(n) 4th step: see the pattern
6
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 if (A[mid] > key) return BS(A, key, start, mid-1) return BS(A, key, mid+1, end)
7
Binary search recursion: running time analysis
1st step: find recurrence equation T(n): running time of BS for input A of size n T(n) = T(n/2) + 1 2nd step: look at termination condition When the search pool is reduced to one T(1) = 1
8
Binary search recursion: running time analysis (cont’d)
3rd step: expand T(n) 4th step: pattern matching
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.