Created
February 13, 2016 10:43
-
-
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
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 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