Commit 91cc490

mo khan <mo@mokhan.ca>
2014-07-29 02:23:10
optimize performance of quick union by maintaining balance.
1 parent 800887e
Changed files (1)
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)