Skip to content

Instantly share code, notes, and snippets.

@t0dd
Last active December 21, 2015 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t0dd/6335330 to your computer and use it in GitHub Desktop.
Save t0dd/6335330 to your computer and use it in GitHub Desktop.
Ruby implementation of the quick-union algorithm
class QuickUnion
def initialize(n)
@id = Array.new(n) {|i| i}
end
def root(i)
while i != @id[i] do
i = @id[i]
end
i
end
def connected?(p, q)
root(p) == root(q)
end
def union(p, q)
@id[p] = root(@id[q])
end
def print_union
puts "#{@id}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment