Algorithm analysis - find maximum value

Function MAX( n, x[] )
  best := x1
  for j := 2 to n do
     if xj > best then best := xj
  return best

How many times is the assignment   "best := xj"   executed?

Let An = the number of new maxima encountered.
Consider the case of n distinct numbers in which all n! possible relative orderings are equally likely.

Hn  ≤  1 + ∫1n dx / x  =  1 + ln n

Hn  ≥  ∫0n dx / (x+1)  =  ln (n+1)

Hn  =  ln n + γ + &Theta(1/n),     where γ = Euler's constant ≈ 0.577


Dan Hirschberg
Last modified: Oct 28, 2003