|
| 1 | +import { kahnTopologicalSort } from '../KahnsAlgorithm.js' |
| 2 | + |
| 3 | +describe("Kahn's Algorithm - Topological Sort", () => { |
| 4 | + test('returns a valid topological order for a DAG', () => { |
| 5 | + const V = 6 |
| 6 | + const edges = [ |
| 7 | + [5, 2], |
| 8 | + [5, 0], |
| 9 | + [4, 0], |
| 10 | + [4, 1], |
| 11 | + [2, 3], |
| 12 | + [3, 1] |
| 13 | + ] |
| 14 | + |
| 15 | + const order = kahnTopologicalSort(V, edges) |
| 16 | + expect(order.length).toBe(V) |
| 17 | + |
| 18 | + // verify topological property |
| 19 | + const pos = new Array(V) |
| 20 | + for (let i = 0; i < order.length; i++) pos[order[i]] = i |
| 21 | + |
| 22 | + for (const [u, v] of edges) { |
| 23 | + expect(pos[u]).toBeLessThan(pos[v]) |
| 24 | + } |
| 25 | + }) |
| 26 | + |
| 27 | + test('returns empty array when graph contains a cycle', () => { |
| 28 | + const V = 3 |
| 29 | + const edges = [ |
| 30 | + [0, 1], |
| 31 | + [1, 2], |
| 32 | + [2, 0] // cycle |
| 33 | + ] |
| 34 | + const order = kahnTopologicalSort(V, edges) |
| 35 | + expect(order).toEqual([]) |
| 36 | + }) |
| 37 | + |
| 38 | + test('includes isolated nodes', () => { |
| 39 | + const V = 4 |
| 40 | + const edges = [ |
| 41 | + [0, 1], |
| 42 | + [2, 3] |
| 43 | + ] |
| 44 | + |
| 45 | + const order = kahnTopologicalSort(V, edges) |
| 46 | + expect(order.length).toBe(V) |
| 47 | + |
| 48 | + const pos = new Array(V) |
| 49 | + for (let i = 0; i < order.length; i++) pos[order[i]] = i |
| 50 | + |
| 51 | + for (const [u, v] of edges) { |
| 52 | + expect(pos[u]).toBeLessThan(pos[v]) |
| 53 | + } |
| 54 | + }) |
| 55 | + |
| 56 | + test('works with empty graph', () => { |
| 57 | + const V = 0 |
| 58 | + const edges = [] |
| 59 | + const order = kahnTopologicalSort(V, edges) |
| 60 | + expect(order).toEqual([]) |
| 61 | + }) |
| 62 | +}) |
0 commit comments