Skip to content

Commit 65b9773

Browse files
committed
DisjointSets Update
DisjointSets Update
1 parent 3689607 commit 65b9773

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
1.58 KB
Binary file not shown.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*Copyright (c) Dec 25, 2014 CareerMonk Publications and others.
2+
* E-Mail : info@careermonk.com
3+
* Creation Date : 2015-01-10 06:15:46
4+
* Last modification : 2006-05-31
5+
by : Narasimha Karumanchi
6+
* File Name : DisjointSets.java
7+
* Book Title : Data Structures And Algorithms Made In Java
8+
* Warranty : This software is provided "as is" without any
9+
* warranty; without even the implied warranty of
10+
* merchantability or fitness for a particular purpose.
11+
*
12+
*/
13+
14+
15+
package chapter08disjointsets;
16+
17+
public class DisjointSets {
18+
19+
private int[] S;
20+
public DisjointSets(int numElements) {
21+
S = new int [numElements];
22+
for (int i = 0; i < S.length; i++) {
23+
S[i] = -1;
24+
}
25+
}
26+
27+
public void union(int root1, int root2) {
28+
if (S[root2] < S[root1]) {
29+
S[root1] = root2;
30+
} else {
31+
if (S[root1] == S[root2]) {
32+
S[root1]--;
33+
}
34+
S[root2] = root1;
35+
}
36+
}
37+
38+
// Path Compression
39+
public int find(int x) {
40+
if (S[x] < 0) {
41+
return x;
42+
} else {
43+
S[x] = find(S[x]);
44+
return S[x];
45+
}
46+
}
47+
48+
public static void main(String[] args) {
49+
int NumElements = 97;
50+
int NumInSameSet = 14;
51+
52+
DisjointSets s = new DisjointSets(NumElements);
53+
int set1, set2;
54+
55+
for (int k = 1; k < NumInSameSet; k *= 2) {
56+
for (int j = 0; j + k < NumElements; j += 2 * k) {
57+
set1 = s.find(j);
58+
set2 = s.find(j + k);
59+
s.union(set1, set2);
60+
}
61+
}
62+
63+
for (int i = 0; i < NumElements; i++) {
64+
System.out.print(s.find(i) + "*");
65+
if (i % NumInSameSet == NumInSameSet - 1) {
66+
System.out.println();
67+
}
68+
}
69+
System.out.println();
70+
}
71+
}

0 commit comments

Comments
 (0)