Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift implementation of the weighted quick union algorithm, useful for applications requiring percolation
class WQU {
var data = [0,1,2,3,4,5]
var size = [1,1,1,1,1,1]
func union(a:Int, b:Int) {
let i = root(a)
let j = root(b)
if size[i] >= size[j] {
size[i] += size[j]
data[j] = data[i]
}
else {
size[j] += size[i]
data[i] = data[j]
}
}
// get the root
func root(i:Int) -> Int {
var j = i
while j != data[j] {
j = data[j]
}
return j
}
}
// useage:
var wqu = WQU()
wqu.union(1, b: 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.