Skip to content

Fix topological sort order#14688

Open
Sean-Kenneth-Doherty wants to merge 1 commit into
TheAlgorithms:masterfrom
Sean-Kenneth-Doherty:codex/topological-sort-order
Open

Fix topological sort order#14688
Sean-Kenneth-Doherty wants to merge 1 commit into
TheAlgorithms:masterfrom
Sean-Kenneth-Doherty:codex/topological-sort-order

Conversation

@Sean-Kenneth-Doherty
Copy link
Copy Markdown

Fixes #12192.

The DFS implementation appended nodes after visiting their descendants and returned that postorder directly, which placed dependents before their prerequisites. This keeps the existing implementation shape but inserts each completed node at the front of the output so every edge source appears before its targets.

I also added a doctest for the module sample graph.

Validation:

  • python -m doctest -v sorts/topological_sort.py
  • python sorts/topological_sort.py
  • python - <<'PY'\nfrom sorts.topological_sort import edges, topological_sort\norder = topological_sort('a', [], [])\nposition = {node: index for index, node in enumerate(order)}\nprint(order)\nprint(all(position[src] < position[dst] for src, neighbors in edges.items() for dst in neighbors))\nPY\n- uv run --no-project --with pytest python -m pytest sorts/topological_sort.py -q\n- uv run --no-project --with ruff ruff check sorts/topological_sort.py

@Sean-Kenneth-Doherty Sean-Kenneth-Doherty marked this pull request as ready for review May 16, 2026 22:06
@Sean-Kenneth-Doherty
Copy link
Copy Markdown
Author

Moved out of draft after a final pass over the diff and the current CI state.

Validation visible on the PR is green for build, ruff, Sphinx docs, and pre-commit.ci. The change stays scoped to returning a topological order with each source before its reachable targets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

topological sort returns reversed list

1 participant