Finds the root of the set containing the element i. Uses path compression to flatten the structure. @param i the element to find @return the root of the set
(int i)
| 43 | * @return the root of the set |
| 44 | */ |
| 45 | public int find(int i) { |
| 46 | int parent = p[i]; |
| 47 | |
| 48 | if (i == parent) { |
| 49 | return i; |
| 50 | } |
| 51 | |
| 52 | // Path compression |
| 53 | final int result = find(parent); |
| 54 | p[i] = result; |
| 55 | return result; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Unites the sets containing elements x and y. |