Quick Find (Eager Approach)
I attempted to write the QF/UF function in JS below was my attempt:
class UF { constructor(n) { this.id = []; for (let i = 0; i < n; i++) { this.id[i] = i; } }
connected(p, q) { return this.id[p] == this.id[q]; }
union(p, q) { const pid = this.id[p]; const qid = this.id[q]; for (let i = 0; i < this.id.length; i++) { if (this.id[i] == pid) { this.id[i] = qid; } } }}
const test = new UF(10);console.log(test.id);test.union(1, 4);console.log(test.connected(1, 4));
The Quick Find Union option is expensive due to the number of times the code needs to access the array to initialise and create unions which both go through the entire array as an example N union on N objects would take quadratic time (squared time) - Quadratic time is much to slow for large problems
Quadratic algorithms don’t scale and get slower as our sets grow.