Quick Find
and Quick Union were slow in performing union and finding if two elements are connected respectively. However, Quick Union can be improvised by using weighted trees. The idea here is to avoid tall trees of Quick Union and always balance the trees such that smaller trees always link up to the larger trees.
We use array to initialize elements to indices itself. To weigh trees, we use an extra array to track the size of trees at each element.
Any node x's depth increases by one when it's tree T1 is merged into another T2.
As |T2|>=|T1| , the size of tree containing x at least doubles.
As N*lg N = N, the size of tree containing x can double at most lg N times.
So the depth of any node at x is at most lg N.
Running Time:
initialize - N
union(p,q) - lg N+ - including the root calculations
connected(p,q) - lg N - proportional to depth of p and q
Following is the program:
We use array to initialize elements to indices itself. To weigh trees, we use an extra array to track the size of trees at each element.
Any node x's depth increases by one when it's tree T1 is merged into another T2.
As |T2|>=|T1| , the size of tree containing x at least doubles.
As N*lg N = N, the size of tree containing x can double at most lg N times.
So the depth of any node at x is at most lg N.
Running Time:
initialize - N
union(p,q) - lg N+ - including the root calculations
connected(p,q) - lg N - proportional to depth of p and q
Following is the program:
No comments:
Post a Comment