File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ package Array ;
2
+
3
+ public class DisjointSet {
4
+ private Set [] sets ;
5
+ private int count ;
6
+
7
+ public DisjointSet (int [] elements , int count ){
8
+ sets = new Set [count ];
9
+ for (int i = 0 ; i < count ; i ++){
10
+ sets [i ] = new Set (elements [i ], i );
11
+ }
12
+ this .count = count ;
13
+ }
14
+
15
+ public int findSetRecursive (int index ){
16
+ int parent = sets [index ].getParent ();
17
+ if (parent != index ){
18
+ return findSetRecursive (parent );
19
+ }
20
+ return parent ;
21
+ }
22
+
23
+ public int findSetIterative (int index ){
24
+ int parent = sets [index ].getParent ();
25
+ while (parent != index ){
26
+ index = parent ;
27
+ parent = sets [index ].getParent ();
28
+ }
29
+ return parent ;
30
+ }
31
+
32
+ public void unionOfSets (int index1 , int index2 ){
33
+ int x = findSetIterative (index1 );
34
+ int y = findSetIterative (index2 );
35
+ if (sets [x ].getDepth () < sets [y ].getDepth ()){
36
+ sets [x ].setParent (y );
37
+ } else {
38
+ sets [y ].setParent (x );
39
+ if (sets [x ].getDepth () == sets [y ].getDepth ()){
40
+ sets [x ].incrementDepth ();
41
+ }
42
+ }
43
+ }
44
+ }
Original file line number Diff line number Diff line change
1
+ package Array ;
2
+
3
+ public class Set {
4
+ private int data ;
5
+ private int parent ;
6
+ private int depth ;
7
+
8
+ public Set (int data , int index ){
9
+ this .data = data ;
10
+ parent = index ;
11
+ depth = 1 ;
12
+ }
13
+
14
+ public int getParent () {
15
+ return parent ;
16
+ }
17
+
18
+ public int getDepth () {
19
+ return depth ;
20
+ }
21
+
22
+ public void setParent (int parent ){
23
+ this .parent = parent ;
24
+ }
25
+
26
+ public void incrementDepth (){
27
+ depth ++;
28
+ }
29
+ }
You can’t perform that action at this time.
0 commit comments