I have these two find algorithm which look the same to me. Can anyone help me out why they are actually different?
Find ( x ) :
if x.parent = x then
return x
else
return Find ( x.parent )
vs
Find ( x ) :
if x.parent = x then
return x
else
x.parent <- Find(x.parent)
return x.parent
I interpret the first one as
int i = 0;
return i++;
while the second one as
int i = 0;
int tmp = i++;
return tmp
which are exactly the same to me.
This looks like Disjoint-set data structure.
Now to the question:
For the sake of clarity first version is
FindA, second isFindB.Suppose you have structure:
First call to
FindA(n)will return 0 in O(n), second call will return 0 in O(n) and so on.If you call
FindB(n)it will return 0 in O(n), but will also modify structure:Now second call to FindB(n) will return 0 in O(1). More over FindB(k) will return 0 in O(1).