Last active
December 21, 2015 16:39
-
-
Save t0dd/6335330 to your computer and use it in GitHub Desktop.
Ruby implementation of the quick-union algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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