Commit 91cc490
Changed files (1)
lib
lib/quick_union.rb
@@ -1,10 +1,21 @@
class QuickUnion
def initialize(size)
@items = Array.new(size) { |n| n }
+ @size = Array.new(size, 0)
end
def union(x, y)
- @items[x] = root_of(y)
+ i = root_of(x)
+ j = root_of(y)
+ return if (i == j)
+
+ if @size[i] < @size[j]
+ @items[i] = j
+ @size[j] = @size[j] + @size[i]
+ else
+ @items[j] = i
+ @size[i] = @size[i] + @size[j]
+ end
end
def connected?(x, y)