Algorithm Analysis¶
Basic Notations¶
We must have some notation to better describe our algorithm.
Definitions
(i) We call
(ii) We call
(iii) we call
(iv) we call
Or less formally,
The following rules are usually really useful for algorithm analysis.
Rules
(i) If
(ii) If
(Proved by find
(iii)
Recursions¶
We take Merge Sort as an example.
Merge(A, p, q, r)
n1 = q - p + 1
n2 = r - q
L[1...(n1 + 1)]
R[1...(n2 + 1)]
for i = 1 to n1
L[i] = A[p + i - 1]
for j = 1 to n2
R[j] = A[q + j]
L(n1 + 1) = R(n2 + 1) = +inf
for k = p to r
if L[i] <= R[j]
A[k] = L[i]
i = i + 1
else
A[k] = R[j]
j = j + 1
whose time cost is
MergeSort(A, p, r)
if p < r
q = (p + r) / 2
MergeSort(A, p, q)
MergeSort(A, q + 1, r)
Merge(A, p, q, r)
Assume the time cost of MergeSort is
It is apparent to draw a graph of tree for this recursion, get its time cost and then prove it using Induction.
Generalize the above thoughts and we have the following theorem.
Master Theorem
Assume
where
(i) If there exists
(ii) If
(iii) If there exists
The above
The focus is to compare the relative size between
Q1. Solve for time cost
(i)
(ii)
(iii)
which does not satisfy (i), (ii) of Master Theorem, so we need to confirm if it satisfies the regularity condition of (iii) in Master Theorem. Notice that
So if we choose
So it satisfies (iii) of Master Theorem. Thus time cost
Notice that there exists gap between (i) and (ii) in Master Theorem, cause some function may not satisfy
(i)
(ii)
The above two could not be solved by Master Theorem. We have to use recursive tree.
Divide & Conquer¶
- 二分搜索
BinarySearch(A, x)
left, right = 0, len(A)-1
while left<=right:
mid = (left+right)/2
if(x==A[mid]):
return mid;
else if (A[mid]<x):
left = mid+1;
else if (A[mid]>x):
right = mid-1;
return -1;
BinarySearch(A, x, left, right)
if left> right:
return -1;
mid = (left+right)/2;
if(A[mid]==x):
return mid;
else if (A[mid]<x):
return BinarySearch(A,x, mid+1,right);
else if (A[mid]>x):
return BinarySearch(A,x, left, mid-1);
time cost