Professional Documents
Culture Documents
Problem
To emphasize algorithm analysis, we will consider
the problem of finding the maximum sum of a
contiguous subsequence of integers from a given
input data sequence.
For example, if the input data sequence contains
CSCI 3320/8325
Data Structures
2 11 4 13
Module 2
First Algorithms for Analysis
5 2
The Solutions
Algorithm 1: Analysis
Right Half
4 -3 5 -2
-1 2 6 -2
10
c = (l + r) / 2;
// approximate center
maxlsum = maxSumRec(a,0,c);
// solve left part
maxrsum = maxSumRec(a,c+1,a.size()); // right part
lbsum=0, maxlbsum=0; // left border sum
(int i=c; i>=l; i--) {
lbsum += a[i];
if (lbsum > maxlbsum) maxlbsum = lbsum;
12
Algorithm 3: Analysis
If we consider only the base case for the recursion (a single
element), it is clear that T (1) = O (1), since only one of
two return statements is executed.
If more than one element is in the subsequence, then we
recursively invoke the function with the left and right halves
of the original vector, each taking time T (N /2), then
compute the sum of (potentially all) the elements in the
vector, taking time O (N ). Thus the total worst case
running time for the recursive cases is
T (N ) = 2 T (N /2) + O (N ).
13
14
15
16
17
18
Algorithm 4: Analysis
19
Binary Search
20
21
22
Euclids Algorithm
//
//
//
//
#1
#2
#3
#3
// #4
25
26
Exponentiation
Computation of a b (where a and b are both
integers) can be done using the obvious technique
involving b 1 multiplications.
We can do better than this is we observe that if z
= a k, then z ? z = a 2 k.
Thus, if b is even, a b = (a 2) b / 2, eliminating
almost half of the multiplications required by the
obvious technique.
27
//
//
//
//
//
28
Exponentiation: Analysis
The base cases for the recursive function
(statements 1 and 2) clearly take O (1) time.
Each recursive invocation of pow reduces the size
of the exponent by a constant factor (2), so the
running time is logarithmic.
If we count the number of multiplications, its easy
to see that at most two multiplications are involved
for each invocation of the function, so the
maximum number of multiplications is 2 log2 b.
#1
#2
#3
#4
#5
29
30