Skip to content

Instantly share code, notes, and snippets.

@timrichardsn
Created February 13, 2016 10:43
Show Gist options
  • Save timrichardsn/e85ef805289415a0da20 to your computer and use it in GitHub Desktop.
Save timrichardsn/e85ef805289415a0da20 to your computer and use it in GitHub Desktop.
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