Skip to content

Commit 2d0466d

Browse files
Merge pull request #404 from jvanvugt/joris/path-halving-union-find
Use path halving in unionfind to improve performance
2 parents b1381d3 + 717dab5 commit 2d0466d

File tree

1 file changed

+7
-13
lines changed

1 file changed

+7
-13
lines changed

common/unionfind.h

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -82,26 +82,20 @@ static inline uint32_t unionfind_get_representative(unionfind_t *uf, uint32_t id
8282
// version above.
8383
static inline uint32_t unionfind_get_representative(unionfind_t *uf, uint32_t id)
8484
{
85-
uint32_t root = uf->parent[id];
8685
// unititialized node, so set to self
87-
if (root == 0xffffffff) {
86+
if (uf->parent[id] == 0xffffffff) {
8887
uf->parent[id] = id;
8988
return id;
9089
}
9190

92-
// chase down the root
93-
while (uf->parent[root] != root) {
94-
root = uf->parent[root];
91+
// Path halving: make every node point to its grandparent (single pass)
92+
// This is simpler and faster than full path compression while still effective
93+
while (uf->parent[id] != id) {
94+
uf->parent[id] = uf->parent[uf->parent[id]]; // Point to grandparent
95+
id = uf->parent[id]; // Move to grandparent
9596
}
9697

97-
// go back and collapse the tree.
98-
while (uf->parent[id] != root) {
99-
uint32_t tmp = uf->parent[id];
100-
uf->parent[id] = root;
101-
id = tmp;
102-
}
103-
104-
return root;
98+
return id;
10599
}
106100

107101
static inline uint32_t unionfind_get_set_size(unionfind_t *uf, uint32_t id)

0 commit comments

Comments
 (0)