Dis-Joint Set in Kotlin | Data Structures

A disjoint-set data structure is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets.

A union-find algorithm is an algorithm that performs two useful operations on such a data structure:

Find: Determine which subset a particular element is in. This can be used for determining if two elements are in the same subset.

Union: Join two subsets into a single subset.

``````
class DisjointSet(val size: Int) {
private val parent = IntArray(size)
private val rank = ByteArray(size)
public var count = size
private set
init {
for (i in parent.indices) {
parent[i] = i
}
}
public fun connected(v: Int, w: Int): Boolean {
return find(v) == find(w)
}
public fun find(v: Int): Int {
var v = v
while (parent[v] != v) {
parent[v] = parent[parent[v]]
v = parent[v]
}
return v
}
public fun union(v: Int, w: Int) {
val rootV = find(v)
val rootW = find(w)
if (rootV == rootW) return
if (rank[rootV] > rank[rootW]) {
parent[rootW] = rootV
} else if (rank[rootW] > rank[rootV]) {
parent[rootV] = rootW
} else {
parent[rootV] = rootW
rank[rootW]++
}
count--
}
}
``````

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below