Skip to content

New Algorithm #1675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Graphs/KannsAlgorithm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

/**
* @author {RaviSadam}
* @name kannsAlgorithm
* @description -
* Kann's Algorithm implementation in JavaScript
* @summary
* Kann's Algorithm is used for topological sorting in directed acyclic graphs
*
* @param graph - Graph [[v1,v2],[v3,v4,v5]..]
* @param n - number of vertices
* @returns {Array} - Empty array if cycle is detected or else result array;
*
*/

export function kannsAlgorithm(graph, n) {
if (n === null || n === undefined)
throw Error('Invalid v is given');
const inorder = Array(n).fill(0);
const result = [];
for (let entry of graph) {
for (let edge of entry) {
inorder[edge] += 1;
}
}
const queue = [];
console.log(inorder);
for (let i = 0; i < n; i++) {
if (inorder[i] === 0) {
queue.push(i);
}
}
while (queue.length != 0) {
const node = queue[0];
result.push(node);
queue.splice(0, 1);
for (let nei of graph[node]) {
inorder[nei] -= 1;
if (inorder[nei] == 0) {
queue.push(nei);
}
}
}
if (result.length != n)
return [];
return result;
}
14 changes: 14 additions & 0 deletions Graphs/test/KannsAlgorithm.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { kannsAlgorithm } from "../KannsAlgorithm";

test('Test Case 1: Graph wihout cycle', () => {

Check failure on line 3 in Graphs/test/KannsAlgorithm.test.js

View workflow job for this annotation

GitHub Actions / Check for spelling errors

wihout ==> without
const graph = [[], [], [3], [1], [0, 1], [0, 2]];

expect(kannsAlgorithm(graph, 6)).toEqual([4, 5, 0, 2, 3, 1]);
});

test('Test Case 2: Graph with cycle', () => {

const graph = [[2], [], [3, 5], [0, 1], [0, 2]];

expect(kannsAlgorithm(graph, 6)).toEqual([]);
});
Loading