C
Chris Uppal
Hendrik said:You just misread the OP's exercise, so basically we're both right.
Agreed. As I said in another post, I originally formulated this stuff in a
1-based language, and then translated everthing back by hand (which is why
there are typos in my "example"). I didn't notice that that changed the point
at which you should start following the chain.
It is an interesting question what the complexity is. This will be the
average length of a cycle. Intuitively, I'd say this is n/2. I don't
expect something sublinear here.
I think your intuition must be better than mine. Alexandre posted that the
algorithm had to check around 2/3 of the array (for the N=1000 case). I found
an analysis on the web:
http://www.inference.phy.cam.ac.uk/mackay/itila/cycles.pdf
which states that the average cycle length is:
N / ln(N)
and that the average length of a cycle /passing through a specifed point/ is:
(N+1) / 2
That's for pure permutations, of course. If we assume that in this case the
tail itself is probably as long as the average cycle passing through a
specified point, and that the cycle it joins onto is essentaily random, then
you'd expect to have to check the sum of the above array slots before the
search terminates. In the case where N=1000 that works out to about 650, so it
might not be too far off as an estimate. If that's true then it is O(N).
-- chris