File: union_find.c

package info (click to toggle)
linux 6.12.43-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,676,260 kB
  • sloc: ansic: 25,921,022; asm: 269,579; sh: 136,424; python: 65,440; makefile: 55,721; perl: 37,752; xml: 19,284; cpp: 5,895; yacc: 4,927; lex: 2,939; awk: 1,594; sed: 28; ruby: 25
file content (49 lines) | stat: -rw-r--r-- 1,172 bytes parent folder | download | duplicates (17)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// SPDX-License-Identifier: GPL-2.0
#include <linux/union_find.h>

/**
 * uf_find - Find the root of a node and perform path compression
 * @node: the node to find the root of
 *
 * This function returns the root of the node by following the parent
 * pointers. It also performs path compression, making the tree shallower.
 *
 * Returns the root node of the set containing node.
 */
struct uf_node *uf_find(struct uf_node *node)
{
	struct uf_node *parent;

	while (node->parent != node) {
		parent = node->parent;
		node->parent = parent->parent;
		node = parent;
	}
	return node;
}

/**
 * uf_union - Merge two sets, using union by rank
 * @node1: the first node
 * @node2: the second node
 *
 * This function merges the sets containing node1 and node2, by comparing
 * the ranks to keep the tree balanced.
 */
void uf_union(struct uf_node *node1, struct uf_node *node2)
{
	struct uf_node *root1 = uf_find(node1);
	struct uf_node *root2 = uf_find(node2);

	if (root1 == root2)
		return;

	if (root1->rank < root2->rank) {
		root1->parent = root2;
	} else if (root1->rank > root2->rank) {
		root2->parent = root1;
	} else {
		root2->parent = root1;
		root1->rank++;
	}
}