function quickSort(left, right, a, key) { if (left > right) return; var i = left; var j = right; var benchMark = a[i]; var temp; while (i != j) { while (a[j][key] >= benchMark[key] && i < j) j--; while (a[i][key] <= benchMark[key] && i < j) i++; if (i < j) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } a[left] = a[i]; a[i] = benchMark; quickSort(left, i - 1, a, key); quickSort(i + 1, right, a, key); } var MakeSet = (function() { let set = new Set(); return function(x) { x.parent = x; x.rank = 0; if (!set.has(x)) set.add(x); return set; } })(); function Find(x) { if (x.parent != x) x.parent = Find(x.parent); return x.parent; } function Union(u, v) { let uRoot = Find(u); let vRoot = Find(v); if (uRoot == vRoot) return; if (uRoot.rank < vRoot.rank) uRoot.parent = vRoot; else if (uRoot.rank > vRoot.rank) vRoot.parent = uRoot; else { vRoot.parent = uRoot; uRoot.rank = uRoot.rank + 1; } } function Kruskal(G) { let A = []; for(let x of G.V) { MakeSet(x); } for(let e of G.E) { quickSort(0, G.E.length-1, G.E, 'w'); } for(let e of G.E) { let u = G.V[G.refer.get(e.u)]; let v = G.V[G.refer.get(e.v)]; if(Find(u)!=Find(v)) { A.push(e); Union(u, v); } } return A; } function Vertex() { if (!(this instanceof Vertex)) return new Vertex(); this.edges = null; this.id = null; this.data = null; } function Edge() { if (!(this instanceof Edge)) return new Edge(); this.index = null; this.sibling = null; this.w = null; } function Graph() { if (!(this instanceof Graph)) return new Graph(); this.V = []; this.E = []; this.refer = new Map(); } Graph.prototype = { constructor: Graph, //这里加进来的已经具备了边的关系 //创建图的 节点 initVertex: function(vertexs) { for (let v of vertexs) { let vertex = Vertex(); vertex.id = v.id; this.V.push(vertex); } for (let i in this.V) { this.refer.set(this.V[i].id, i); } }, initEdge: (function() { function createLink(index, len, edges, refer) { if (index >= len) return null; let edgeNode = Edge(); edgeNode.index = refer.get(edges[index].id); edgeNode.w = edges[index].w; edgeNode.sibling = createLink(++index, len, edges, refer); return edgeNode; } return function(edges) { for (let field in edges) { let index = this.refer.get(field); let vertex = this.V[index]; vertex.edges = createLink(0, edges[field].length, edges[field], this.refer); } } }()), storageEdge: function(edges) { this.E = edges; } } var vertexs = [{id:'a'}, {id:'b'}, {id:'c'}, {id:'d'}, {id:'e'}]; var edges = [ {u:'a',v:'b',w:3}, {u:'a',v:'c',w:1}, {u:'b',v:'a',w:3}, {u:'b',v:'c',w:4}, {u:'b',v:'d',w:5}, {u:'c',v:'a',w:1}, {u:'c',v:'b',w:4}, {u:'c',v:'d',w:6}, {u:'c',v:'e',w:7}, {u:'d',v:'b',w:5}, {u:'d',v:'c',w:6}, {u:'d',v:'e',w:2}, {u:'e',v:'c',w:7}, {u:'e',v:'d',w:6} ] var g = Graph(); g.initVertex(vertexs); g.storageEdge(edges); var A = Kruskal(g); console.log(A);
|