Skip to content

Commit b0f22e6

Browse files
authored
Merge pull request thuva4#181 from Sudeepa14/master
Added the Javascript implementation
2 parents cd4a167 + 495ce69 commit b0f22e6

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

Dijkstra's /Javascript

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
function dijkstra(g, source) {
2+
/* initially, all distances are infinite and all predecessors are null */
3+
for(var n in g.nodes)
4+
g.nodes[n].distance = Infinity;
5+
/* predecessors are implicitly null */
6+
7+
source.distance = 0;
8+
var counter = 0;
9+
/* set of unoptimized nodes, sorted by their distance (but a Fibonacci heap
10+
would be better) */
11+
var q = new BinaryMinHeap(g.nodes, "distance");
12+
13+
var node;
14+
/* get the node with the smallest distance */
15+
/* as long as we have unoptimized nodes */
16+
17+
while(q.min() != undefined) {
18+
/* remove the latest */
19+
node = q.extractMin();
20+
node.optimized = true;
21+
22+
/* no nodes accessible from this one, should not happen */
23+
if(node.distance == Infinity)
24+
throw "Orphaned node!";
25+
26+
/* for each neighbour of node */
27+
for(e in node.edges) {
28+
if(node.edges[e].target.optimized)
29+
continue;
30+
31+
/* look for an alternative route */
32+
var alt = node.distance + node.edges[e].weight;
33+
34+
/* update distance and route if a better one has been found */
35+
if (alt < node.edges[e].target.distance) {
36+
37+
/* update distance of neighbour */
38+
node.edges[e].target.distance = alt;
39+
40+
/* update priority queue */
41+
q.heapify();
42+
43+
/* update path */
44+
node.edges[e].target.predecessor = node;
45+
}
46+
}
47+
}
48+
}

QuickSort/Javascript

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function quickSort(items, left, right) {
2+
3+
var index;
4+
5+
if (items.length > 1) {
6+
7+
left = typeof left != "number" ? 0 : left;
8+
right = typeof right != "number" ? items.length - 1 : right;
9+
10+
index = partition(items, left, right);
11+
12+
if (left < index - 1) {
13+
quickSort(items, left, index - 1);
14+
}
15+
16+
if (index < right) {
17+
quickSort(items, index, right);
18+
}
19+
20+
}
21+
22+
return items;
23+
}
24+
25+
// first call
26+
var result = quickSort(items);

0 commit comments

Comments
 (0)