Proof of
average running time of max()
recall that the code for max:
def maximum(A, n): # # of RAM operations, type of operation v = float('-inf') # 1, Assigning a value for i in range(n): # 3n + 1, # n Arithmetic operation (i + 1) # n Assigning a value (i = i + 1) # n + 1 Comparison operation (i < n) if A[i] > v: # n, Comparison operation v = A[i] # X, # a random variable X that has (0 < X <= 2n) return v # 1
Assume
all possible orderings are equally likely (meaning each value has a equall probability being the largest value of the subarray A[0-i])
all n elements of A are distinct
update takes O(1)
Key idea
The running maximum gets updated on iteration i if and only if max([A[0] ... A[i]]) = A[i]. Since the probability of each value being the largest value of the subarray is known, we can calculate the total expected update count of this algorithm.
Set up indicator random variable Xi
if v updated on iteration i
Xi = 1
else
Xi = 0
The distribution of Xi
The Expectation of Xi
Total exact updates
Total expected updates
which reduce to the nth harmonic number
because (gamma is Euler's constant)
The average case running time T(n) of max(A, n) is
文案 / CUCS学术部 梁力天
编辑 / CUCS宣传部
© CUCS 2020.10