Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
78 lines (75 loc) · 1.91 KB

File metadata and controls

78 lines (75 loc) · 1.91 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Keeps track of a set of elements partitioned into a
* number of disjoint (nonoverlapping) subsets.
* Allows to check whether the path between two nodes exists.
* The algorithm is inspired by Robert Sedgewick's Java implementation.
* <br>
* The algorithm is inspired by Robert Sedgewick's Java implementation.
* For further reading http://algs4.cs.princeton.edu/home/.
*
* @example
*
* var QuickFind = require('path-to-algorithms/src/sets/quickfind').QuickFind;
*
* var qfind = new QuickFind(10);
* qfind.union(0, 1);
* qfind.union(2, 1);
* qfind.union(3, 4);
* qfind.union(8, 9);
* qfind.union(4, 8);
*
* console.log(qfind.connected(0, 9)); // false
* console.log(qfind.connected(3, 9)); // true
*
* @public
* @module sets/quickfind
*/
(function (exports) {
'use strict';
/**
* Initialization.<br><br>
* Time complexity: O(N).
*
* @public
* @constructor
* @param {Numner} size Count of the nodes.
*/
exports.QuickFind = function (size) {
this._ids = [];
for (var i = 0; i < size; i += 1) {
this._ids[i] = i;
}
};
/**
* Connects two nodes - p and q.<br><br>
* Time complexity: O(N).
*
* @public
* @method
* @param {Number} p The first node.
* @param {Number} q The second node.
*/
exports.QuickFind.prototype.union = function (p, q) {
var size = this._ids.length;
var pval = this._ids[p];
var qval = this._ids[q];
for (var i = 0; i < size; i += 1) {
if (this._ids[i] === qval) {
this._ids[i] = pval;
}
}
};
/**
* Checks whether two nodes are connected.<br><br>
* Time complexity: O(1).
*
* @public
* @method
* @param {Number} p The first node.
* @param {Number} q The second node.
* @return {Boolean}
*/
exports.QuickFind.prototype.connected = function (p, q) {
return this._ids[p] === this._ids[q];
};
})(typeof window === 'undefined' ? module.exports : window);
Morty Proxy This is a proxified and sanitized view of the page, visit original site.