union_find.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/union_find.h>
  3. /**
  4. * uf_find - Find the root of a node and perform path compression
  5. * @node: the node to find the root of
  6. *
  7. * This function returns the root of the node by following the parent
  8. * pointers. It also performs path compression, making the tree shallower.
  9. *
  10. * Returns the root node of the set containing node.
  11. */
  12. struct uf_node *uf_find(struct uf_node *node)
  13. {
  14. struct uf_node *parent;
  15. while (node->parent != node) {
  16. parent = node->parent;
  17. node->parent = parent->parent;
  18. node = parent;
  19. }
  20. return node;
  21. }
  22. /**
  23. * uf_union - Merge two sets, using union by rank
  24. * @node1: the first node
  25. * @node2: the second node
  26. *
  27. * This function merges the sets containing node1 and node2, by comparing
  28. * the ranks to keep the tree balanced.
  29. */
  30. void uf_union(struct uf_node *node1, struct uf_node *node2)
  31. {
  32. struct uf_node *root1 = uf_find(node1);
  33. struct uf_node *root2 = uf_find(node2);
  34. if (root1 == root2)
  35. return;
  36. if (root1->rank < root2->rank) {
  37. root1->parent = root2;
  38. } else if (root1->rank > root2->rank) {
  39. root2->parent = root1;
  40. } else {
  41. root2->parent = root1;
  42. root1->rank++;
  43. }
  44. }