Quick Union

Implementation of Quick Union algorithm

by Alex Myronov

Babel + JSX

const root = (item, ids) => {
	let temp = item
  while (temp !== _ids[temp]) {
  	temp = _ids[temp]
  }
  return temp
}

class QuickUnion {
	constructor(n) {
  	this._ids = []
    for	(let i = 0; i < n; i++) {
    	this._ids[i] = i
    }
  }
  
  union(p, q) {
  	const pRoot = root(p, this._ids)
  	const qRoot = root(q, this._ids)
    this._ids[pRoot] = qRoot
  }
  
  connected(p, q) {
	  return root(p, this._ids) === root(q, this._ids)
  }
}