Skip to content

Commit ded5e99

Browse files
committed
Quick union: improve performance using size array.
1 parent 4b00a1c commit ded5e99

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

Diff for: union-find/weighted-quick-union/solution.rb

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class WeightedQU
2+
attr_reader :size, :values, :sizes
3+
4+
def initialize(size)
5+
@size = size
6+
@values = Array.new(@size)
7+
@sizes = Array.new(@size)
8+
(0...@size).each do |i|
9+
@values[i] = i
10+
end
11+
(0...@size).each do |i|
12+
@sizes[i] = 1
13+
end
14+
end
15+
16+
def root(p)
17+
root = p
18+
while(root != @values[root])
19+
root = @values[root]
20+
end
21+
root
22+
end
23+
24+
def connected(p, q)
25+
return root(p) == root(q)
26+
end
27+
28+
def union(p, q)
29+
pr = root(p)
30+
qr = root(q)
31+
return if pr == qr
32+
if(@sizes[pr] >= @sizes[qr])
33+
@values[qr] = pr
34+
@sizes[pr] += @sizes[qr]
35+
else
36+
@values[pr] = qr
37+
@sizes[qr] += @sizes[pr]
38+
end
39+
end
40+
end

Diff for: union-find/weighted-quick-union/spec.rb

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
require_relative './solution.rb'
2+
3+
RSpec.describe WeightedQU do
4+
let(:wquick_union) { WeightedQU.new(10)}
5+
6+
it "Test the values assigned" do
7+
expect(wquick_union.size).to eq(10)
8+
expect(wquick_union.values.size).to eq(10)
9+
expect(wquick_union.sizes.size).to eq(10)
10+
end
11+
12+
it "Check if two elements are connected" do
13+
expect(wquick_union.connected(0, 1)).to eq(false)
14+
end
15+
16+
it "Test the algorithm" do
17+
wquick_union.union(4, 3)
18+
expect(wquick_union.values).to eq([0, 1, 2, 4, 4, 5, 6, 7, 8, 9])
19+
wquick_union.union(9, 8)
20+
expect(wquick_union.values).to eq([0, 1, 2, 4, 4, 5, 6, 7, 9, 9])
21+
wquick_union.union(9, 7)
22+
expect(wquick_union.values).to eq([0, 1, 2, 4, 4, 5, 6, 9, 9, 9])
23+
wquick_union.union(3, 7)
24+
expect(wquick_union.values).to eq([0, 1, 2, 4, 9, 5, 6, 9, 9, 9])
25+
wquick_union.union(6, 7)
26+
expect(wquick_union.values).to eq([0, 1, 2, 4, 9, 5, 9, 9, 9, 9])
27+
28+
expect(wquick_union.sizes[9]).to eq(6)
29+
end
30+
31+
it "Get the root element of an element" do
32+
wquick_union.union(6, 7)
33+
expect(wquick_union.root(7)).to eq(6)
34+
end
35+
36+
it "Check if two elements are connected" do
37+
wquick_union.union(0, 1)
38+
wquick_union.union(1, 2)
39+
wquick_union.union(2, 3)
40+
expect(wquick_union.connected(0, 3)).to eq(true)
41+
end
42+
end

0 commit comments

Comments
 (0)