Skip to content

Commit eac1c0d

Browse files
author
nars
committed
Added weighted union
1 parent b01bec4 commit eac1c0d

File tree

4 files changed

+65
-7
lines changed

4 files changed

+65
-7
lines changed

UnionFindAlgo/src/UnionFindRunner.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
import implemenation.QuickUnionImpl;
1+
import implemenation.WeightedUnionImpl;
22

33
/**
44
* Created by nars on 2/24/15.
55
*/
66
public class UnionFindRunner {
7-
public static QuickUnionImpl unionUnionImpl = new QuickUnionImpl();
7+
// public static QuickUnionImpl unionUnionImpl = new QuickUnionImpl();
8+
public static WeightedUnionImpl unionUnionImpl = new WeightedUnionImpl();
89
public static void main(String[] args) {
910
unionUnionImpl.process("/Users/nars/Dev/DragonRepo/JavaDevelopment/UnionFindAlgo/src/input.txt");
1011
}

UnionFindAlgo/src/implemenation/QuickUnionImpl.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public boolean find(int p, int q) {
2424
public void union(int p, int q) {
2525
if (! find(p, q))
2626
{
27-
setRootOf(p, getRootOf(q));
27+
this.setRootOf(p, getRootOf(q));
2828
}
2929
}
3030

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package implemenation;
2+
3+
/**
4+
* Created by nars on 3/10/15.
5+
*/
6+
public class WeightedUnionImpl extends QuickUnionImpl{
7+
8+
int[] weightArray = null;
9+
10+
public void initializeInput() {
11+
this.initInputArraySize();
12+
weightArray = new int[this.getInputSize()];
13+
for (int i = 0; i < this.getInputSize(); i++) {
14+
this.setElementAt(i,i);
15+
this.setWeightAt(i,1);
16+
}
17+
}
18+
19+
public void setWeightAt(int index, int value)
20+
{
21+
this.weightArray[index] = value;
22+
}
23+
public int getWeightAt(int index)
24+
{
25+
return this.weightArray[index];
26+
}
27+
28+
public void union(int p, int q) {
29+
if (! find(p, q))
30+
{
31+
int rootWeightOfP= this.getWeightAt(this.getRootOf(p));
32+
int rootWeightOfQ= this.getWeightAt(this.getRootOf(q));
33+
if (rootWeightOfP < rootWeightOfQ)
34+
{
35+
this.setRootOf(p, getRootOf(q));
36+
}
37+
else
38+
{
39+
this.setRootOf(q, getRootOf(p));
40+
}
41+
}
42+
}
43+
44+
public void setRootOf(int nodeP, int newRoot) {
45+
int currentWeight = this.getWeightAt(getRootOf(nodeP));
46+
int newRootWeight = this.getWeightAt(newRoot);
47+
this.setElementAt(getRootOf(nodeP), newRoot);
48+
this.setWeightAt(newRoot, currentWeight+newRootWeight);
49+
}
50+
51+
}

UnionFindAlgo/src/input.txt

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
4
2-
F 1 2
3-
U 1 2
4-
F 1 2
1+
10
2+
U 3 4
3+
U 4 9
4+
U 8 0
5+
U 2 3
6+
U 5 6
7+
U 5 9
8+
U 7 3
9+
U 4 8
10+
U 6 1

0 commit comments

Comments
 (0)