Completed
Push — master ( 42e858...e23440 )
by Siro Díaz
02:43
created

DisjointNode   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 11
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 1
c 1
b 0
f 1
lcom 0
cbo 0
dl 0
loc 11
rs 10
1
<?php
2
/**
3
 * DataStructures for PHP
4
 *
5
 * @link      https://github.com/SiroDiaz/DataStructures
6
 * @copyright Copyright (c) 2017 Siro Díaz Palazón
7
 * @license   https://github.com/SiroDiaz/DataStructures/blob/master/README.md (MIT License)
8
 */
9
namespace DataStructures\Sets;
10
11
use DataStructures\Trees\Nodes\DisjointNode;
12
13
/**
14
 * DisjointSet.
15
 *
16
 * The DisjointSet class represents a disjoint set.
17
 * Operations take in worse case a O(n) except makeSet that takes
18
 * constant time, O(1).
19
 * Basic operations are makeSet, find and union.
20
 *
21
 * @author Siro Diaz Palazon <[email protected]>
22
 */
23
class DisjointSet {
24
    public function __construct() {}
25
26
    public function makeSet($data) {
27
        $newSet = new DisjointNode(0, $data);
28
        $newSet->parent = &$newSet;
29
30
        return $newSet;
31
    }
32
33
    public function find(DisjointNode $node) : DisjointNode {
34
        if($node->parent !== $node) {
35
            $node->parent = $this->find($node->parent);
36
        }
37
38
        return $node->parent;
39
    }
40
41
    public function union($x, $y) {
42
        $rootX = $this->find($x);
43
        $rootY = $this->find($y);
44
45
        if($rootX === $rootY) {
46
            return;
47
        }
48
49
        if($rootX->rank < $rootY->rank) {
50
            $rootX->parent = &$rootY;
51
        } else if($rootX->rank > $rootY->rank) {
52
            $rootY->parent = &$rootX;
53
        } else {
54
            $rootX->parent = &$rootY;
55
            $rootY->rank++;
56
        }
57
    }
58
}